| 1 |
class InputHistory { |
| 2 |
constructor() { |
| 3 |
this.states = []; |
| 4 |
this.currentIndex = 0; |
| 5 |
} |
| 6 |
get currentState() { |
| 7 |
return this.states[this.currentIndex]; |
| 8 |
} |
| 9 |
get isEmpty() { |
| 10 |
return this.states.length === 0; |
| 11 |
} |
| 12 |
push(state) { |
| 13 |
// if current index points before the last element then remove the future |
| 14 |
if (this.currentIndex < this.states.length - 1) this.states.length = this.currentIndex + 1; |
| 15 |
this.states.push(state); |
| 16 |
if (this.states.length > InputHistory.MAX_LENGTH) this.states.shift(); |
| 17 |
this.currentIndex = this.states.length - 1; |
| 18 |
} |
| 19 |
go(steps) { |
| 20 |
this.currentIndex = Math.min(Math.max(this.currentIndex + steps, 0), this.states.length - 1); |
| 21 |
return this.currentState; |
| 22 |
} |
| 23 |
undo() { |
| 24 |
return this.go(-1); |
| 25 |
} |
| 26 |
redo() { |
| 27 |
return this.go(+1); |
| 28 |
} |
| 29 |
clear() { |
| 30 |
this.states.length = 0; |
| 31 |
this.currentIndex = 0; |
| 32 |
} |
| 33 |
} |
| 34 |
InputHistory.MAX_LENGTH = 100; |
| 35 |
|
| 36 |
export { InputHistory as default }; |
| 37 |
|