Skip to content

Instantly share code, notes, and snippets.

@mfbx9da4
Last active May 12, 2021 14:06
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 mfbx9da4/efea90762f32e3443489947488b7779b to your computer and use it in GitHub Desktop.
Save mfbx9da4/efea90762f32e3443489947488b7779b to your computer and use it in GitHub Desktop.
a = new VersionedMap(); // v0
console.assert(a.version === 0, "a.version === 0");
console.assert(a.isSame(a), "a.isSame(a)");
// mutate a producing b v1
b = a.set(1, 1);
console.assert(a.version === 0, "a.version === 0");
console.assert(b.version === 1, "b.version === 1");
console.assert(!a.isSame(a), "!a.isSame(a)");
console.assert(!a.isSame(b), "!a.isSame(b)");
console.assert(b.isSame(b), "!a.isSame(b)");
// no change so stay on v1
c = b.set(1, 1);
console.assert(b.version === 1, "b.version === 1");
console.assert(b.version === 1, "b.version === 1");
console.assert(b.isSame(b), "b.isSame(b)");
console.assert(b.isSame(c), "b.isSame(c)");
console.assert(c.isSame(c), "c.isSame(c)");
class VersionedMap {
constructor(iterableOrMap, version = 0) {
this.map =
iterableOrMap instanceof Map ? iterableOrMap : new Map(iterableOrMap);
this.version = version;
this.mutated = false;
}
set(key, value) {
if (this.map.get(key) !== value) {
this.map.set(key, value);
this.mutated = true;
return new VersionedMap(this.map, this.version + 1);
}
return this;
}
delete(key) {
if (this.map.has(key)) {
this.map.delete(key);
this.mutated = true;
return new VersionedMap(this.map, this.version + 1);
}
return this;
}
isSame(versionedMap) {
return (
!this.mutated &&
versionedMap instanceof VersionedMap &&
!versionedMap.mutated &&
versionedMap.map instanceof Map &&
versionedMap.map === this.map &&
versionedMap.version === this.version
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment