Skip to content

Instantly share code, notes, and snippets.

@rbrahul
Created May 13, 2023 22:36
Show Gist options
  • Save rbrahul/2d1719087f6551836ec804cd13f59d64 to your computer and use it in GitHub Desktop.
Save rbrahul/2d1719087f6551836ec804cd13f59d64 to your computer and use it in GitHub Desktop.
Simple implementation of Undo and Redo With State History
class StateHistory{
historyIndex = 0;
initialState = {num: 1};
stateHistory = [this.initialState];
setState(fn){
this.stateHistory = [...this.stateHistory, fn(this.stateHistory[this.historyIndex])];
this.historyIndex++;
}
get hasUndo(){
return this.historyIndex > 0;
}
get hasRedo(){
return this.historyIndex < this.stateHistory.length - 1;
}
redo(fn) {
if(this.hasRedo) {
this.historyIndex++
fn(this.stateHistory[this.historyIndex]);
}
}
undo(fn){
if(this.hasUndo) {
this.historyIndex--;
fn(this.stateHistory[this.historyIndex]);
}
}
}
const state = new StateHistory();
state.setState((curr) => {
console.log("Current State",curr)
return {
num:5
};
});
state.setState(() => {
return {
num:6
};
});
state.setState(() => {
return {
num:7
};
});
state.undo((prevState) => {
console.log("prevState:",prevState) // Will be { num: 6 }
})
console.log(state.hasRedo); // Will be true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment