DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Behavioral - Memento

Image description

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 };
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (1)

Collapse
 
jangelodev profile image
Joรฃo Angelo

Hi Nhan Nguyen,
Top, very nice and helpful !
Thanks for sharing.