Skip to content

Instantly share code, notes, and snippets.

@A-gambit
Created January 3, 2017 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A-gambit/1660b10f592729e4f33c99117e43b890 to your computer and use it in GitHub Desktop.
Save A-gambit/1660b10f592729e4f33c99117e43b890 to your computer and use it in GitHub Desktop.
export class UndoAtom<T> {
private _atom: Atom<T>
_undo: Array<T>
_redo: Array<T>
constructor(atom: Atom<T>) {
this._atom = atom
this._undo = []
this._redo = []
this._atom.subscribe(x => this._undo.push(x))
}
static create(atom: Atom<any>): UndoAtom<any> {
return new UndoAtom(atom)
}
undo() {
const newState = this._undo.pop()
const currentState = this._atom.get()
if (newState) {
this._atom.set(newState)
this._redo.push(currentState)
}
}
redo() {
const newState = this._undo.pop()
const currentState = this._atom.get()
if (newState) {
this._atom.set(newState)
this._undo.push(currentState)
}
}
get undoCount() {
return this._undo.length
}
get redoCount() {
return this._redo.length
}
get atom(): Atom<T> {
return this._atom
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment