Learn how to avoid mutating arrays using concat(), slice(), and the ES6 array spread operator.
Is there a library of non-mutative array methods? Rewriting versions of Array.prototype.splice
over and over to avoid mutation seems a bit crazy. :p
Check out https://github.com/kolodny/immutability-helper.
Avoiding mutations is made way easier with Immutable JS:
const addCounter = list => {
return list.push(0);
};
const removeCounter = (list, index) => {
return list.remove(index);
};
const incrementCounter = (list, index) => {
return list.update(index, i => i + 1);
};
const testAddCounter = () => {
const listBefore = List();
const listAfter = List([0]);
expect(addCounter(listBefore)).toEqual(listAfter);
expect(listBefore.size).toEqual(0);
};
const testRemoveCounter = () => {
const listBefore = List([0, 10, 20]);
const listAfter = List([0, 20]);
expect(removeCounter(listBefore, 1)).toEqual(listAfter);
};
const testIncrementCounter = () => {
const listBefore = List([0, 1, 2]);
const listAfter = List([0, 1, 3]);
expect(incrementCounter(listBefore, 2)).toEqual(listAfter);
};
testAddCounter();
testRemoveCounter();
testIncrementCounter();
console.info("all tests passed");
What are the performance tradeoffs for ensuring the immutability of an array with a large object graph, with potentially thousands of objects with nested objects within them? I'm assuming returning a new array builds an entirely new copy in memory or is it using pointers to the source array?
Just taking this course now; I get a deepFreeze is undefined
error. However, I noticed Object.freeze
is built in and gets the error I want.
Just taking this course now; I get a
deepFreeze is undefined
error. However, I noticedObject.freeze
is built in and gets the error I want.
Just remember that if you need to make an object immutable, recursively freeze each property which is of type object (deep freeze). Otherwise you'll have a shallow freeze.