Write an `ImmutableArray` class wrapping an array with `push`, `pop`, `set(index, val)` methods that return new ImmutableArray instances.
Problem Statement
Write an `ImmutableArray` class wrapping an array with `push`, `pop`, `set(index, val)` methods that return new ImmutableArray instances.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Each mutation method returns a NEW instance, not modifying the original.
š” Hint 2:
Use spread or slice to create copies.
š” Hint 3:
push returns new ImmutableArray([...this.items, val]). pop returns new ImmutableArray(this.items.slice(0, -1)).
ā
Solution:
```javascript
class ImmutableArray {
constructor(items = []) { this.items = [...items]; }
push(val) { return new ImmutableArray([...this.items, val]); }
pop() { return new ImmutableArray(this.items.slice(0, -1)); }
set(index, val) { const arr = [...this.items]; arr[index] = val; return new ImmutableArray(arr); }
toArray() { return [...this.items]; }
}
```