Skip to content

Instantly share code, notes, and snippets.

@carrotflakes
Created June 7, 2019 15:01
Show Gist options
  • Save carrotflakes/a7a366c94b4f99b9ff3bd1d867d13ac7 to your computer and use it in GitHub Desktop.
Save carrotflakes/a7a366c94b4f99b9ff3bd1d867d13ac7 to your computer and use it in GitHub Desktop.
const commands = {
add: {
do(state, action) {
return {
num: state.num + action.x
};
},
undo(state, action) {
return {
num: state.num - action.x
};
},
},
mul: {
do(state, action) {
return {
num: state.num * action.x
};
},
undo(state, action) {
return {
num: state.num / action.x
};
},
},
};
class StateManager {
constructor() {
this.state = {
num: 0
};
this.history = [];
this.historyI = 0;
}
print() {
console.log(this.state);
}
invoke(action) {
this.history.push(action);
this.redo();
}
undo() {
const action = this.history[--this.historyI];
this.state = commands[action.type].undo(this.state, action);
}
redo() {
const action = this.history[this.historyI++];
this.state = commands[action.type].do(this.state, action);
}
}
const sm = new StateManager();
sm.print();
sm.invoke({type: 'add', x: 3});
sm.print();
sm.invoke({type: 'mul', x: 2});
sm.print();
sm.invoke({type: 'add', x: -2});
sm.print();
sm.invoke({type: 'mul', x: 5});
sm.print();
sm.undo();
sm.undo();
sm.undo();
sm.print();
sm.redo();
sm.redo();
sm.redo();
sm.print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment