Explorer
Node.js

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]; } } ```

Immutable Array Operations

Hard
Write an `ImmutableArray` class wrapping an array with `push`, `pop`, `set(index, val)` methods that return new ImmutableArray instances.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"a":[1,2,3],"b":[1,2,3,4],"c":[1,2,3],"different":true}