Last active
May 12, 2021 14:06
-
-
Save mfbx9da4/efea90762f32e3443489947488b7779b 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
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)"); |
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
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