Last active
November 19, 2016 02:09
-
-
Save mgtitimoli/93086279819227100140542be01a46f8 to your computer and use it in GitHub Desktop.
Tiny immutable set implementation
This file contains hidden or 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 o1 = {k1: {k2: false}}; | |
const o2 = setImmutable(o1, ["k1", "k2"], true); | |
console.log(o1 === o2); // false | |
console.log(o1.k1 === o2.k1); // false | |
console.log(o1.k1.k2 === o2.k1.k2); // false |
This file contains hidden or 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 shallowClone = objectOrArray => ( | |
Array.isArray(objectOrArray) ? | |
Array.from(objectOrArray) : | |
Object.assign({}, objectOrArray) | |
); | |
const setAndReturn = (object, key, value) => { | |
object[key] = value; | |
return value; | |
}; | |
const ensureImmutable = (root, path) => path | |
.slice(0, -1) | |
.reduce((current, segment, index) => setAndReturn( | |
current, | |
segment, | |
segment in current ? | |
shallowClone(current[segment]) : | |
getSegmentValue(path[index + 1]) | |
), root); | |
const setWith = (ensure, root, path, value) => { | |
const destination = ensure(root, path); | |
const key = path[path.length - 1]; | |
destination[key] = value; | |
return root; | |
}; | |
const setImmutable = (root, path, value) => setWith( | |
ensureImmutable, | |
shallowClone(root), | |
path, | |
value | |
); | |
export default setImmutable; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment