Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
19.12. An array whose methods never mutate
Medium
Topics
This question is in
19. Events, state and historyA list in shared state, such as the rows of a table that several components read, must not change under them. If one component calls rows.sort(), every other component's rows are sorted too, and nothing re-renders because the array is the same object. A safer list makes that mistake impossible: its mutating methods return a new list, and any direct write fails loudly.
Write immutableArray(items) in immutable-array.js.
Signature
function immutableArray(items) // returns an immutable arrayitems: an array or any other iterable. It is copied and never changed.- The result is a real array for
Array.isArray,length, indexes,for...of, spreading andJSON.stringify.
Requirements
- The result holds a copy of
items; changingitemslater changes nothing, anditemsitself is not frozen. - These methods return a new immutable array and leave the old one unchanged:
push(...values): the values appendedpop()andshift(): without the last or the first value (an empty array stays empty)unshift(...values): the values in frontsplice(start, deleteCount, ...values): the array after the change, with the usual rules for negative and missing argumentssort(compare): a sorted copy, with the default order ofArray.prototype.sortwhencompareis missingreverse(),fill(value, start, end),copyWithin(target, start, end): changed copies
with(index, value),map,filter,sliceandconcatalso return immutable arrays.withthrows aRangeErrorfor an index outside the array, as the built-in does.- Methods that return one value (
find,indexOf,includes,joinand others) return it unchanged, even when that value is an array. - Callbacks (
forEach,map...) receive the immutable array itself as their third argument. - Assigning an index,
lengthor any property throws aTypeError, in strict and non-strict code alike. So dodeleteandObject.defineProperty, and so does calling a built-in mutator on it directly (Array.prototype.push.call(array, 4)).Object.isFrozen(array)istrue. - It is shallow: the elements are the same values, not copies.
Examples
const rows = immutableArray([3, 1, 2]);
const sorted = rows.sort(); // [1, 2, 3], a new immutable array
rows; // still [3, 1, 2]
rows.push(4); // [3, 1, 2, 4]
rows.splice(0, 1); // [1, 2]: the array after the changeconst rows = immutableArray(["a", "b"]);
rows[0] = "z"; // TypeError, even in non-strict code
rows.length = 0; // TypeErrorimmutableArray([10, 1, undefined, 2]).sort(); // [1, 10, 2, undefined]: strings order, undefined last
immutableArray([]).pop(); // []Environment
- Plain JavaScript in a browser page; the tests call the global
immutableArrayfromimmutable-array.js. - The built-ins
toSorted,toSpliced,toReversedandwithare allowed. - Deep immutability (freezing the elements), holes and subclasses of
Arrayare not part of this problem.
Hints
Object.freezemakes writes fail, but in non-strict code a failed write is silent. What can intercept the write so it throws?- A method such as
pushis not on the array itself but onArray.prototype. What happens when you return your own function for the key"push"?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…