Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active November 19, 2016 02:09
Show Gist options
  • Save mgtitimoli/93086279819227100140542be01a46f8 to your computer and use it in GitHub Desktop.
Save mgtitimoli/93086279819227100140542be01a46f8 to your computer and use it in GitHub Desktop.
Tiny immutable set implementation
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
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