DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

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 };
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:

Neon image

Set up a Neon project in seconds and connect from a Next.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

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

Heroku

Save time with this productivity hack.

See how Heroku MCP Server connects tools like Cursor to Heroku, so you can build, deploy, and manage apps—right from your editor.

Learn More

👋 Kindness is contagious

Dive into this insightful article, celebrated by the caring DEV Community. Programmers from all walks of life are invited to share and expand our collective wisdom.

A simple thank-you can make someone’s day—drop your kudos in the comments!

On DEV, spreading knowledge paves the way and strengthens our community ties. If this piece helped you, a brief note of appreciation to the author truly counts.

Let’s Go!