Skip to content

Instantly share code, notes, and snippets.

@bjdixon
Created July 30, 2015 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjdixon/0fba149fd8c3073f5edd to your computer and use it in GitHub Desktop.
Save bjdixon/0fba149fd8c3073f5edd to your computer and use it in GitHub Desktop.
A Model with undo and redo stacks
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