class HistoryNavigator { history: (string | number)[]; currIndex: number; historyLimit: number | undefined; constructor(history?: (string | number)[], historyLimit?: number) { this.history = history && history.length > 0 ? history : ['']; this.currIndex = this.history.length - 1; this.historyLimit = historyLimit; } reset = (newHistory?: (string | number)[], historyLimit = 20) => { this.history = newHistory && newHistory.length > 0 ? newHistory : ['']; this.currIndex = this.history.length - 1; this.historyLimit = historyLimit; }; add = (element: string | number) => { if (!this.historyLimit || this.history.length <= this.historyLimit) { this.history.push(element); // Always keep the current Index to the latest change this.currIndex = this.history.length - 1; } else { // @TODO not needed now but maybe it can be useful to implement a limit. this.currIndex = this.history.length - 1; } }; redo = () => { const historyLength = this.history.length; this.currIndex = this.currIndex + 1 < historyLength ? this.currIndex + 1 : historyLength - 1; return this.history[this.currIndex]; }; undo = () => { this.currIndex = this.currIndex - 1 > 0 ? this.currIndex - 1 : 0; return this.history[this.currIndex]; }; } export default HistoryNavigator;