Mutate-immutable-arrays-in-javascript
In my work with QML, I needed a way to mutate an immutable array. It’s surprisingly easy to do this in Javascript. In this article, I give an outline of the technique followed by working Javascript code.
The Outline
Variables
Let S, A, and I be zero-based arrays.
Let A be an immutable array
Let I be empty
Let N be an integer with initial value 0
Let S[i]=i+1 for all i in {0..||A||}
Let a positive value in S indicate an element of A: S[i] indicates A[S[i] – 1].
Let a negative value in S indicate an element of I: S[i] indicates I[-S[i] – 1]
S is the mutable “face” of A.
Let N indicate the next unused element of I.
Pseudocode
To insert an object X into S at index i:
To remove an object from S at index i:
To change an the object at S[i] to X:
The value of S[i] is
Bugs?
It may be possible for I to grow without bound.
The Code
This code assumes