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:

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

Top comments (1)

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

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

DevCycle image

Ship Faster, Stay Flexible.

DevCycle is the first feature flag platform with OpenFeature built-in to every open source SDK, designed to help developers ship faster while avoiding vendor-lock in.

Start shipping