Memento

by Artem

JavaScript

'use strict';

class SearchFilter {
  constructor(options) {
    Object.keys(options).forEach(optionKey => {
      this[optionKey] = options[optionKey];
    });
  }
  save() {
    const memento = new Memento();
    memento.setState(this);
    return memento;
  }
  load(memento) {
    const state = memento.getState();
    this.name = state.name;
    this.age = state.age
  }
}

class Memento {
  getState() {
    return JSON.parse(this.state);
  }
  setState(state) {
    this.state = JSON.stringify(state);
  }
}

class CareTaker {
  constructor() {
    this._snapshots = [];
  }
  setSnapshot(snapshot) {
    const id = Math.random();
    this._snapshots.push({
      id,
      snapshot
    });
    return id;
  }
  getSnapshot(id) {
    return this._snapshots.find(snapshot => snapshot.id === id).snapshot;
  }
}

const filter = new SearchFilter({
  name: 'Artem',
  age: 21
});
const careTaker = new CareTaker();
const id1 = careTaker.setSnapshot(filter.save());

filter.name = 'Illuxa';
filter.age = 25;
const id2 = careTaker.setSnapshot(filter.save());

filter.load(careTaker.getSnapshot(id1));
console.log(filter);

filter.load(careTaker.getSnapshot(id2));
console.log(filter);