An add operation records an item that appears in the target array but cannot be found in the working array from the current index onward. It inserts that item at the target index. section 7.6.1 section 7.6.4
Build the operation in three small responsibilities:
- Check whether the target item exists in the working array starting at the current index; treat a missing match as an addition. section 7.6.2 section 7.6.4
- Create { op: 'add', index, item } to describe the insertion. section 7.6.1 section 7.6.4
- Insert the item into the working array and record -1 as its original index because it was absent from the initial array. section 7.6.4
Inserting K
With oldArray = [X, A, A, B, C] and newArray = [C, K, A, B], the algorithm reaches index 1 with K as the target item. No K exists in the working array from index 1 onward, so it inserts K at index 1 and appends an add operation. section 7.6.3
[
{op: 'remove', index: 0, item: 'A'}
{op: 'move', originalIndex: 2, from: 1, index: 0, item: 'C'}
{op: 'noop', index: 1, originalIndex: 1, item: 'B'}
{op: 'add', index: 2, item: 'D'}
]
Browse a complete operation sequence showing an add alongside remove, move, and noop operations. section 7.6.1
