DEV Community

Discussion on: Get immutable versions of Array methods

Collapse
 
prodigalknight profile image
RevanProdigalKnight • Edited

pop, push, shift, unshift, and splice are not, and never were intended to be, immutable methods. The intended use of these is to allow JavaScript arrays to emulate a Stack or Queue object without needing to actually define a separate object in the language. Notably, pop, shift, and splice return the element(s) removed from the array, if any, so that they can be used in certain kinds of loops, i.e.:

const arr = [1, 2, 3, 4, 5];

while (arr.length > 0) {
  const element = arr.pop();

  if (element % 2 === 0) {
    arr.push(element + 1);
  }
}

Now, this is a rather simplistic example, but when trying to navigate the layers of a tree in a dynamic fashion (rather than using recursion), the pattern becomes very useful:

const nodes = [node];

while (nodes.length > 0) {
  const n = nodes.pop();

  /* do something with the node */

  if (node.hasChildren()) {
    nodes.push(...node.getChildren());
  }
}

Your immutable replacements for this would not be usable in this case as they are now.

I would suggest that your immutable replacements for these functions return an array consisting of the new array in the first element and then what the result of the non-immutable original function would be in the second element, e.g.:

import { pop } from '@immutable-array/pop';
import { push } from '@immutable-array/push';
const arr = [1, 2, 3, 4, 5];

const popResult = pop(arr);

console.log(popResult); // [[1, 2, 3, 4], 5]

const pushResult = push(arr, 6);

console.log(pushResult); // [[1, 2, 3, 4, 5, 6], 6]