Skip to content

Instantly share code, notes, and snippets.

@toriaezunama
Created August 21, 2016 23:21
Show Gist options
  • Save toriaezunama/8d090df752641b573a050d241a8881bf to your computer and use it in GitHub Desktop.
Save toriaezunama/8d090df752641b573a050d241a8881bf to your computer and use it in GitHub Desktop.
Immutable state issues in js
const y = {
a: 'hi',
b: 4.5,
c: [1,2,3],
d: {
e: 'e',
f: {
g: 55
}
}
};
console.log(y);
const y2 = {...y}; // shallow copy
console.log(y === y2); // false - y2 is a new object
console.log(y.c === y2.c); // true - c is a reference
console.log(y.d === y.d); // true - d is a reference
y.c.push(4);
console.log(y.c);
console.log(y.c === y2.c); // true - c was mutated in place. we have no way to know c changed
const y3 = Object.assign({}, y, {c: y.c.slice()});
console.log(y3);
console.log(y3 === y); // false - new object created
console.log(y3.d === y.d); // true - structural sharing
// no way to mutate a nested object
const y4 = Object.assign({}, y, {d: {f: { g: 55}}}); // overwrites/replaces d with a whole new object
console.log(y4);
// solution
const y5 = Object.assign({}, y, {d: Object.assign({}, y.d, {f: Object.assign({}, y.d.f, { g: 66})})});
console.log(y5);
// cleaner syntax
const y6 = { ...y, d: {...y.d, f: {...y.d.f, g: 66}}}; // still prone to making errors when compared with paths
console.dir(y6, y6.d.f);
// if only ....
//const y7 = {...y, d.f.g: 66}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment