Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created January 26, 2025 04:33
Show Gist options
  • Save allenhwkim/ea23aeb4ba2684d4cf928c3a120a4554 to your computer and use it in GitHub Desktop.
Save allenhwkim/ea23aeb4ba2684d4cf928c3a120a4554 to your computer and use it in GitHub Desktop.
UndoRedo
import structuredClone from "@ungap/structured-clone";
export const UndoRedo = {
debounceMs: 300,
timeout: 0,
undoStack: [],
redoStack: [],
reset(item) {
this.undoStack = [structuredClone(item)];
},
undo() {
if (this.undoStack.length) {
const action = this.undoStack.shift();
this.redoStack.unshift(action);
return action;
}
},
redo(){
if (this.redoStack.length) {
const action = this.redoStack.shift();
this.undoStack.unshift(action);
return action;
}
},
addHistory(item){
// clearTimeout(this.timeout);
// this.timeout = setTimeout(() => {
this.undoStack.unshift(item);
this.redoStack = [];
// }, this.debounceMs);
},
};
UndoRedo.debounceMs = 0;
let checks = [];
UndoRedo.addHistory(1);
UndoRedo.addHistory(2);
UndoRedo.addHistory(3);
UndoRedo.addHistory(4);
UndoRedo.addHistory(5);
checks = [];
checks.push(UndoRedo.undo()); // 5
checks.push(UndoRedo.undo()); // 4
checks.push(UndoRedo.undo()); // 3
checks.push(UndoRedo.undo()); // 2
checks.push(UndoRedo.undo()); // 1
checks.push(UndoRedo.undo()); // undefined;
console.log('check 1...', checks);
checks = [];
checks.push(UndoRedo.redo()); // 1
checks.push(UndoRedo.redo()); // 2
checks.push(UndoRedo.redo()); // 3
checks.push(UndoRedo.redo()); // 4
checks.push(UndoRedo.redo()); // 5
checks.push(UndoRedo.redo()); // undefined
console.log('check 2...', checks);
checks = [];
checks.push(UndoRedo.undo()); // 5
checks.push(UndoRedo.undo()); // 4
UndoRedo.addHistory(10);
UndoRedo.addHistory(20);
UndoRedo.addHistory(30);
checks.push(UndoRedo.undo()); // 30
checks.push(UndoRedo.undo()); // 20
checks.push(UndoRedo.undo()); // 10
checks.push(UndoRedo.undo()); // 3
checks.push(UndoRedo.undo()); // 2
checks.push(UndoRedo.undo()); // 1
checks.push(UndoRedo.undo()); // undefined
console.log('checks 3 ...', checks);
checks = [];
checks.push(UndoRedo.redo()); // 1
checks.push(UndoRedo.redo()); // 2
checks.push(UndoRedo.redo()); // 3
checks.push(UndoRedo.redo()); // 10
checks.push(UndoRedo.redo()); // 20
checks.push(UndoRedo.redo()); // 30
checks.push(UndoRedo.redo()); // undefined
console.log('checks 4 ...', checks);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment