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:

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay