Skip to main content

Command Palette

Search for a command to run...

JavaScript Design Patterns - Behavioral - Memento

Published
1 min read
N

I'm Nhan. I'm a web developer from Vietnam. I have over 5 years of experience in the Angular framework.

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:

More from this blog

Nhan Nguyen's blog

88 posts

I’m a web developer, and I am really passionate about learning web development.