Skip to curriculum
Jump to the editor

19.12. An array whose methods never mutate

Medium
Topics
20–35 min

A 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

JAVASCRIPT
function immutableArray(items) // returns an immutable array
  • items: 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 and JSON.stringify.

Requirements

  1. The result holds a copy of items; changing items later changes nothing, and items itself is not frozen.
  2. These methods return a new immutable array and leave the old one unchanged:
    • push(...values): the values appended
    • pop() and shift(): without the last or the first value (an empty array stays empty)
    • unshift(...values): the values in front
    • splice(start, deleteCount, ...values): the array after the change, with the usual rules for negative and missing arguments
    • sort(compare): a sorted copy, with the default order of Array.prototype.sort when compare is missing
    • reverse(), fill(value, start, end), copyWithin(target, start, end): changed copies
  3. with(index, value), map, filter, slice and concat also return immutable arrays. with throws a RangeError for an index outside the array, as the built-in does.
  4. Methods that return one value (find, indexOf, includes, join and others) return it unchanged, even when that value is an array.
  5. Callbacks (forEach, map...) receive the immutable array itself as their third argument.
  6. Assigning an index, length or any property throws a TypeError, in strict and non-strict code alike. So do delete and Object.defineProperty, and so does calling a built-in mutator on it directly (Array.prototype.push.call(array, 4)). Object.isFrozen(array) is true.
  7. It is shallow: the elements are the same values, not copies.

Examples

JAVASCRIPT
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 change
JAVASCRIPT
const rows = immutableArray(["a", "b"]);
rows[0] = "z";                    // TypeError, even in non-strict code
rows.length = 0;                  // TypeError
JAVASCRIPT
immutableArray([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 immutableArray from immutable-array.js.
  • The built-ins toSorted, toSpliced, toReversed and with are allowed.
  • Deep immutability (freezing the elements), holes and subclasses of Array are not part of this problem.

Hints

  1. Object.freeze makes writes fail, but in non-strict code a failed write is silent. What can intercept the write so it throws?
  2. A method such as push is not on the array itself but on Array.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…