Skip to content

Instantly share code, notes, and snippets.

@rafaelrinaldi
Created September 2, 2022 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelrinaldi/e3ead7df37bf97bec59af4958bf0651c to your computer and use it in GitHub Desktop.
Save rafaelrinaldi/e3ead7df37bf97bec59af4958bf0651c to your computer and use it in GitHub Desktop.
const assert = require("assert");
class Doc {
constructor(layers) {
this.layers = layers.reduce((accumulator, current) => {
const { id, properties } = current;
return {
...accumulator,
[id]: properties,
};
}, {});
this.actions = [];
}
layerById(id) {
const properties = this.layers[id];
return {
id,
properties,
};
}
apply(id, property, value) {
const properties = this.layers[id] ?? {};
this.layers[id] = {
...properties,
[property]: value,
};
this.actions.push([id, property, value]);
}
undo() {
if (this.actions.length < 2) return;
const [id, property, value] = this.actions[this.actions.length - 2];
const properties = this.layers[id];
this.layers[id] = {
...properties,
[property]: value,
};
this.actions.pop();
}
}
const doc = new Doc([
{ id: "a", properties: { color: "red" } },
{ id: "b", properties: { shape: "rect" } },
]);
// Initialized values should be present on the layers object on bootstrap
assert.deepEqual(doc.layerById("a"), {
id: "a",
properties: { color: "red" },
});
assert.deepEqual(doc.layerById("b"), {
id: "b",
properties: { shape: "rect" },
});
doc.apply("a", "color", "green");
// New `a` color should be `green
assert.deepEqual(doc.layerById("a"), {
id: "a",
properties: { color: "green" },
});
doc.apply("a", "color", "blue");
doc.apply("a", "color", "gold");
doc.apply("a", "color", "fuchsia");
doc.undo();
assert.deepEqual(doc.layerById("a"), {
id: "a",
properties: { color: "gold" },
});
doc.undo();
assert.deepEqual(doc.layerById("a"), {
id: "a",
properties: { color: "blue" },
});
doc.undo();
assert.deepEqual(doc.layerById("a"), {
id: "a",
properties: { color: "green" },
});
doc.apply("a", "color", "magenta");
assert.deepEqual(doc.layerById("a"), {
id: "a",
properties: { color: "magenta" },
});
doc.undo();
assert.deepEqual(doc.layerById("a"), {
id: "a",
properties: { color: "green" },
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment