A list that never changes in place
React re-renders when a reference changes, and memoised selectors skip work when it has not. That only works if updates produce new objects instead of mutating old ones, which is why persistent, immutable collections keep showing up in state libraries.
Implement an ImmutableList class. new ImmutableList(items) takes an optional array and stores a copy of it, defaulting to an empty list; later changes to the array passed in must not affect the list. push(value) returns a new ImmutableList with the value appended, leaving the original untouched. set(index, value) returns a new ImmutableList with that index replaced, or returns the very same instance (this) when the index is negative or past the end. pop() returns a new ImmutableList without the last value, or the very same instance when the list is already empty. get(index) returns the value at an index, or undefined when out of range. size() returns the number of values. toArray() returns a fresh plain array of the values, so mutating what it returns must not affect the list.
Returning the identical instance when nothing would change is the point: callers compare with === to decide whether to re-render.
What it has to do
push,setandpopnever modify the list they were called on.setwith an out-of-range index returns the same instance rather than a copy.popon an empty list returns the same instance.- The constructor copies its input, so mutating that array afterwards does not change the list.
toArray()returns a fresh array each time.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.