Created
June 7, 2019 15:01
-
-
Save carrotflakes/a7a366c94b4f99b9ff3bd1d867d13ac7 to your computer and use it in GitHub Desktop.
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 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