Skip to content

Commit

Permalink
Merge d24f297 into 81f2baf
Browse files Browse the repository at this point in the history
  • Loading branch information
tusharmath committed Apr 6, 2016
2 parents 81f2baf + d24f297 commit 098ef1a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 29 deletions.
62 changes: 33 additions & 29 deletions index.js
Expand Up @@ -3,67 +3,71 @@
*/

'use strict'

const BehaviorSubject = require('rx').BehaviorSubject
const histable = require('histable')

exports.create = exports.createStoreStream = (value, limit) => {
limit = limit > 0 ? limit : 0
const ignoredValues = {}
const isHistoryEnabled = limit > 0
var history = null

const initHistory = () => {
if (isHistoryEnabled) {
history = histable.create(limit)
history.push(value)
}
}
initHistory()
if (value === undefined) {
value = ignoredValues
}
var UNDO_HISTORY = []
var REDO_HISTORY = []

const subject = new BehaviorSubject(value)
const dispatchValue = (_value, push) => {
var isDefined = _value !== undefined
var isDiff = value !== _value
var isPushable = push === true
var isNotIgnored = value !== ignoredValues
var isHistoryEnabled = limit > 0

if ([isHistoryEnabled, isDefined, !isPushable].every(Boolean)) {
REDO_HISTORY.push(value)
}

if ([isHistoryEnabled, isDefined, isDiff, isPushable, isNotIgnored].every(Boolean)) {
UNDO_HISTORY.push(value)
}

if ([isHistoryEnabled, isDefined, isDiff, isPushable, isNotIgnored, UNDO_HISTORY.length > limit].every(Boolean)) {
UNDO_HISTORY.shift()
}

if ([isDefined, isDiff].every(Boolean)) {
value = _value
subject.onNext(value)
}
}
const reset = () => {
REDO_HISTORY = []
UNDO_HISTORY = []
}

return {
stream: subject.filter(x => x !== ignoredValues),
set: cb => {
REDO_HISTORY = []
dispatchValue(typeof cb === 'function' ? cb(value) : cb, true)
const val = typeof cb === 'function' ? cb(value) : cb
dispatchValue(val)
if (isHistoryEnabled) {
history.push(val)
}
return subject
},
end: () => {
reset()
initHistory()
subject.onCompleted()
},
get: () => value,
undo: () => dispatchValue(UNDO_HISTORY.pop(), false),
redo: () => dispatchValue(REDO_HISTORY.pop(), true),
reset,
undo: () => {
if (isHistoryEnabled) {
dispatchValue(history.undo())
}
},
redo () {
if (isHistoryEnabled) {
dispatchValue(history.redo())
}
},
reset () {
initHistory()
},
get canUndo () {
return UNDO_HISTORY.length > 0
return history.canUndo
},
get canRedo () {
return REDO_HISTORY.length > 0
return history.canRedo
}
}
}
3 changes: 3 additions & 0 deletions package.json
Expand Up @@ -38,5 +38,8 @@
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"dependencies": {
"histable": "^1.1.0"
}
}

0 comments on commit 098ef1a

Please sign in to comment.