JavaScript Design Patterns - Behavioral - Memento
Nhan Nguyen
Posted on July 19, 2024
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 };
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
💖 💪 🙅 🚩
Nhan Nguyen
Posted on July 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.