Created
September 2, 2022 02:50
-
-
Save rafaelrinaldi/e3ead7df37bf97bec59af4958bf0651c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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