JavaScript Design Patterns - Behavioral - Memento

The memento pattern allows capture and externalizes an object’s internal state so that the object can be restored to this state later.

In the example below, we are creating a simple way to store values and restore a snapshot when needed.

class Memento {
  constructor(value) {
    this.value = value;
  }
}

const originator = {
  store: function (val) {
    return new Memento(val);
  },
  restore: function (memento) {
    return memento.value;
  },
};

class Keeper {
  constructor() {
    this.values = [];
  }
  addMemento(memento) {
    this.values.push(memento);
  }
  removeMemento(index) {
    this.values.splice(index, 1);
  }
  getMemento(index) {
    return this.values[index];
  }
  toString() {
    return `[ ${this.values
      .reduce((acc, cur) => {
        acc.push(cur.value);
        return acc;
      }, [])
      .join(', ')} ]`;
  }
}
export { originator, Keeper };

A complete example is here: https://stackblitz.com/edit/vitejs-vite-7mnwye?file=main.js

👉 Use this pattern when you want to produce snapshots of the object’s state to restore a previous state of the object.

I hope you found it helpful. Thanks for reading. 🙏

Let’s get connected! You can find me on: