Skip to content

Commit

Permalink
feat(atom): add IReset/ISwap impls for History
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 31, 2018
1 parent 282d989 commit e1b57de
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions packages/atom/src/history.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { IAtom } from "./api";
import { IAtom, IReset, ISwap, SwapFn } from "./api";

export class History<T> {
export class History<T> implements
IReset<T>,
ISwap<T> {

state: IAtom<T>;
maxLen: number;
Expand All @@ -17,13 +19,6 @@ export class History<T> {
this.future = [];
}

record() {
if (this.history.length == this.maxLen) {
this.history.shift();
}
this.history.push(this.state.deref());
}

undo() {
if (this.history.length) {
this.future.push(this.state.deref());
Expand All @@ -37,4 +32,25 @@ export class History<T> {
return this.state.reset(this.future.pop());
}
}
}

reset(val: T) {
const prev = this.state.deref(),
curr = this.state.reset(val);
curr !== prev && this.record(prev);
return curr;
}

swap(fn: SwapFn<T>, ...args: any[]) {
const prev = this.state.deref(),
curr = this.state.swap.apply(this.state, [fn, ...args]);
curr !== prev && this.record(prev);
return curr;
}

protected record(state: T) {
if (this.history.length == this.maxLen) {
this.history.shift();
}
this.history.push(state);
}
}

0 comments on commit e1b57de

Please sign in to comment.