Frozen list class whose update methods return new lists
A music app keeps the play queue in React state. Every change must produce a new value so React notices it, but writing [...queue.slice(0, i), track, ...queue.slice(i + 1)] everywhere is error-prone, and one stray queue.push() silently breaks rendering. The team wants a small list type that cannot be mutated and whose update methods return new lists.
Implement the class ImmutableList.
const list = new ImmutableList(iterable?);
list.size // number of items
list.get(index) // => item | undefined
list.set(index, value) // => ImmutableList
list.push(...values) // => ImmutableList
list.insert(index, ...values) // => ImmutableList
list.remove(index, count = 1) // => ImmutableList
list.map(fn) // => ImmutableList
list.filter(fn) // => ImmutableList
list.toArray() // => a new plain array
[...list] // lists are iterable
Set, a string…). With no argument, the list is empty. Later changes to the source never affect the list.Object.isFrozen(list) is true), and no property or method exposes the stored items: toArray() returns a fresh copy each time.this), so next === prev tells React to skip a render. Otherwise it returns a new ImmutableList.A negative index counts from the end: -1 is the last item. Normalise it as size + index first. All indexes are integers.
size: a getter.get(index): the item, or undefined if the normalised index is outside 0 … size - 1.set(index, value): replaces one item. Throws a RangeError if the normalised index is outside 0 … size - 1. Returns this if the current item is already value (compared with Object.is).push(...values): appends. Returns this when called with no values.insert(index, ...values): inserts before the item at index; index === size appends. Throws a RangeError if the normalised index is outside 0 … size. Returns this when called with no values (after the range check).remove(index, count = 1): removes up to count items starting at index (fewer if the list ends first). Throws a RangeError if the normalised index is outside 0 … size - 1. Returns this when count is 0 or less (after the range check).map(fn): calls fn(item, index) for every item and always returns a new list of the results.filter(fn): keeps the items for which fn(item, index) is truthy. Returns this if every item is kept.toArray(): a new plain array of the items.[Symbol.iterator](): yields the items in order.const queue = new ImmutableList(['Intro', 'Verse', 'Chorus']);
const next = queue.push('Bridge').set(-1, 'Outro').insert(1, 'Hook');
next.toArray(); // => ['Intro', 'Hook', 'Verse', 'Chorus', 'Outro']
queue.toArray(); // => ['Intro', 'Verse', 'Chorus'] (unchanged)
queue.get(-1); // => 'Chorus'
queue.get(5); // => undefined
queue.set(0, 'Intro') === queue; // => true (nothing changed)
queue.filter(Boolean) === queue; // => true
queue.remove(1, 10).toArray(); // => ['Intro']
queue.set(3, 'Solo'); // throws RangeError
const copy = queue.toArray();
copy.push('Hacked');
queue.size; // => 3