Created
July 30, 2015 16:34
-
-
Save bjdixon/0fba149fd8c3073f5edd to your computer and use it in GitHub Desktop.
A Model with undo and redo stacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const copyObject = (source) => Object.assign({}, source); | |
const Stack = () => { | |
const array = []; | |
return { | |
push (value) { | |
array.push(value); | |
}, | |
pop () { | |
return array.pop(); | |
}, | |
isEmpty () { | |
return !array.length; | |
} | |
}; | |
}; | |
const Model = function (initialAttributes) { | |
let redoStack = Stack(), | |
attributes = copyObject(initialAttributes || {}); | |
const undoStack = Stack(), | |
obj = { | |
set (attrsToSet) { | |
undoStack.push(copyObject(attributes)); | |
if (!redoStack.isEmpty()) { | |
redoStack = Stack(); | |
} | |
for (let key in (attrsToSet || {})) { | |
attributes[key] = attrsToSet[key]; | |
} | |
return obj; | |
}, | |
undo () { | |
if (!undoStack.isEmpty()) { | |
redoStack.push(copyObject(attributes)); | |
attributes = undoStack.pop(); | |
} | |
return obj; | |
}, | |
redo () { | |
if (!redoStack.isEmpty()) { | |
undoStack.push(copyObject(attributes)); | |
attributes = redoStack.pop(); | |
} | |
return obj; | |
}, | |
get (key) { | |
return attributes[key]; | |
}, | |
has (key) { | |
return attributes.hasOwnProperty(key); | |
}, | |
attributes () { | |
return copyObject(attributes); | |
} | |
}; | |
return obj; | |
}; | |
// usage | |
const model = Model(); | |
model.set({"who": "Hartnell"}); | |
model.set({"who": "Troughton"}); | |
console.log(model.get("who")); | |
model.undo(); | |
console.log(model.get("who")); | |
model.redo(); | |
console.log(model.get("who")); | |
model.set({"who": "Pertwee"}); | |
console.log(model.get("who")); | |
model.set({"who": "Baker"}); | |
console.log(model.get("who")); | |
model.undo(); | |
console.log(model.get("who")); | |
model.undo(); | |
console.log(model.get("who")); | |
model.redo(); | |
console.log(model.get("who")); | |
model.redo(); | |
console.log(model.get("who")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment