Skip to content

Instantly share code, notes, and snippets.

@mattlockyer
Last active April 15, 2017 18:13
Show Gist options
  • Save mattlockyer/c42f4d2c232e4af68ca69bf7d73b0ba0 to your computer and use it in GitHub Desktop.
Save mattlockyer/c42f4d2c232e4af68ca69bf7d73b0ba0 to your computer and use it in GitHub Desktop.
Immutability.js as data store with get, set, merge and added undo, redo
const STORE = {
head: new Map(),
undoStack: [],
redoStack: [],
//implement undo
undo: () => {
if (STORE.undoStack.length === 1) return STORE.head;
const action = STORE.undoStack.pop();
STORE.head = STORE.undoStack[STORE.undoStack.length - 1];
STORE.redoStack.push(action);
return action;
},
redo: () => {
if (STORE.redoStack.length === 0) return STORE.head;
STORE.head = STORE.redoStack.pop();
STORE.undoStack.push(STORE.head);
return STORE.head;
}
};
//push empty map
STORE.undoStack.push(STORE.head);
//functions
['get', 'toJS'].forEach(k => STORE[k] = (...args) => STORE.head[k](...args));
['set', 'merge'].forEach(k => STORE[k] = (...args) => {
STORE.head = STORE.head[k](...args);
STORE.undoStack.push(STORE.head);
STORE.redoStack = [];
});
//tests
STORE.set(0, 'zero');
STORE.set(1, 'one');
console.log(STORE.toJS());
STORE.undo();
console.log(STORE.toJS());
STORE.undo();
console.log(STORE.toJS());
STORE.redo();
console.log(STORE.toJS());
STORE.redo();
console.log(STORE.toJS());
STORE.undo();
STORE.set(2, 'two'); //redo erase
STORE.undo();
STORE.undo();
STORE.undo();
STORE.undo(); //no risk undo
STORE.redo();
STORE.redo();
STORE.redo();
STORE.redo(); //no risk redo
console.log(STORE.toJS()); //{0: "zero", 2: "two"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment