Data structure with a fixed number of items of a specific type. Supports adding elements, moving backward and forward with wrapping. Suitable for undo/redo implementations such as history management.
var history = new CircularHistory(5, "string");history.commit("First");
history.commit("Second");Keep in mind that after moving backward, committing a new item will overwrite the items ahead of the current index. It was designed this way to facilitate undo-redo functionality by discarding the "redo" history when a new action is taken.
When the capacity is reached, the oldest items will be overwritten in a circular manner.
var currentItem = history.current();Returns either the current item or CircularHistory.FLAGS.empty if current index is -1 which means there are no committed items yet or you went backwards beyond the first committed item (basically an empty state).
history.moveBackward();
history.moveForward();Moving backward and forward will adjust the current index accordingly and allow you to navigate within specific range which is determined by the number of committed items before navigation. If the number of committed items exceeds the capacity, the range will be limited to the capacity.
history.clear();var historyArray = history.dump();This will return an array of all committed items in the history. If capacity has not been reached, the array will contain items with undefined values for uncommitted slots.
If you want to get only the committed items, you can pass true as an argument.
var committedItems = history.dump(true);var currentIndex = history.getCurrentIndex();var isAtStart = history.isStartReached();
var isAtEnd = history.isEndReached();-
pnpm install -
pnpm test
Imagine that you have a drawing application. You have a layer where you can draw shapes and you can create a snapshot of the layer's state to keep track of changes.
var history = new CircularHistory(50, "string");
function commitHistorySnapshot() {
const snapshot = drawLayer.toJSON();
if (!snapshot) return;
history.commit(snapshot);
}
function restoreHistorySnapshot(snapshot) {
if (!snapshot) return;
if (snapshot === CircularHistory.FLAGS.empty) {
drawLayer.clear();
drawLayer.redraw();
return;
}
drawLayer.unmount();
const restoredLayer = new Layer(snapshot);
drawLayer = restoredLayer;
restoredLayer.redraw();
}
function undo() {
history.moveBackward();
restoreHistorySnapshot(history.current());
}
function redo() {
history.moveForward();
restoreHistorySnapshot(history.current());
}