DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

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:

Sentry image

See why 4M developers consider Sentry, โ€œnot bad.โ€

Fixing code doesnโ€™t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
jangelodev profile image
Joรฃo Angelo โ€ข

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more