简体   繁体   中英

Replace an item at a specific index with vs without mutation

Recently I recently came across these two solution to replace an item at a specific index in an array, but I'm wondering, which one are better and why?

function replace(array, index, item) {
  const newArray = [...array];
  newArray[index] = item;
  return newArray;
}

function replace(array, index, item) {
  return [
    ...array.slice(0, index),
    item,
    ...array.slice(index + 1)
  ];
}

Both functions do exactly the same thing. They both don't modify original array (no mutation) and the only difference is first one simply shallow clone the array before modifying specified index, and second one shallow clone all items before specified index, inserting new value at the specified index and shallow clone the rest of the items.

The first function is better because its 33% faster, since it does the modification in 2 steps vs 3 steps in second function.

If mutation is not an issue, even faster function can be used:

function replace(array, index, item) {
  return array[index] = item;
}

"better" can be subjective. There are several factors you may consider. Some of these:

  • speed: easy to benchmark with realistic data yourself.
  • readability: a matter of opinion.
  • functional programming pattern: the second performs no assignment , so it could be considered by some to better follow the functional programming style
  • response to "invalid" input: for instance, when the given index is greater than the array length, the first solution will produce a sparse array, while the second will just do as if the index was equal to the array length. If the index is -1, the first solution will create negative array properties, which are counter intuitive and do not play a role in most array methods. The second solution will duplicate most of the array, which is weird. For other negative integer values, the second version produces more useful results (the index counts from the back of the array) than the first.

You could also add this version to your list of possible implementations, which is more like the first version:

function replace(array, index, item) {
  return Object.assign([], array, { [index]: item });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM