Core API
timeTravel<T>(initialValue, options?)
Section titled “timeTravel<T>(initialValue, options?)”Creates a time travel instance.
import { timeTravel } from "@biswaviraj/time-travel";
const counter = timeTravel<number>(0);// or with optionsconst editor = timeTravel<string>("hello", { limit: 20 });Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
initialValue | T | The initial state value |
options.limit | number | Max past/future states to keep (default: 10) |
Methods
Section titled “Methods”Returns the current value.
tt.get(); // 0add(value)
Section titled “add(value)”Adds a new state. Clears the redo stack.
tt.add(1);tt.add(2);tt.get(); // 2addMany(values)
Section titled “addMany(values)”Adds multiple states at once. The last element becomes the current value. An empty array is a no-op.
tt.addMany([1, 2, 3]);tt.get(); // 3tt.size; // { past: 3, future: 0 }undo()
Section titled “undo()”Moves back one step. Returns the new value, or undefined if there’s nothing to undo.
tt.undo(); // returns 2tt.undo(); // returns 1tt.undo(); // returns undefined (already at start)redo()
Section titled “redo()”Moves forward one step. Returns the new value, or undefined if there’s nothing to redo.
tt.redo(); // returns 2Jumps n steps through history. Negative values go back, positive values go forward. Returns undefined if out of bounds (state is unchanged).
tt.go(-2); // jump back 2 stepstt.go(1); // jump forward 1 steptt.go(-99); // undefined (out of bounds, state unchanged)reset()
Section titled “reset()”Returns to the initial value and clears all history.
tt.reset();tt.get(); // 0 (initial value)tt.canUndo; // falsett.canRedo; // falsegetHistory()
Section titled “getHistory()”Returns a read-only snapshot of the full history state.
tt.getHistory();// { past: [0, 1], present: 2, future: [3] }subscribe(listener)
Section titled “subscribe(listener)”Registers a listener that fires on any state change. Returns an unsubscribe function.
const unsubscribe = tt.subscribe((state) => { console.log("State changed:", state);});
tt.add(1); // logs "State changed: 1"tt.undo(); // logs "State changed: 0"
unsubscribe();tt.add(2); // no logProperties
Section titled “Properties”canUndo
Section titled “canUndo”boolean — Whether there are past states to undo to.
canRedo
Section titled “canRedo”boolean — Whether there are future states to redo to.
{ past: number; future: number } — Number of steps available in each direction.
tt.size; // { past: 2, future: 1 }type TimeTravelOptions = { limit?: number;};
type TimeTravel<T> = { get(): T; add(value: T): void; addMany(values: T[]): void; undo(): T | undefined; redo(): T | undefined; go(n: number): T | undefined; reset(): void; getHistory(): Readonly<{ past: T[]; present: T; future: T[] }>; subscribe(listener: (state: T) => void): () => void; readonly canUndo: boolean; readonly canRedo: boolean; readonly size: { past: number; future: number };};