Skip to content

Instantly share code, notes, and snippets.

@srph
Last active May 26, 2017 11:40
Show Gist options
  • Select an option

  • Save srph/0da1e135b2562d2cb04b5850ab042255 to your computer and use it in GitHub Desktop.

Select an option

Save srph/0da1e135b2562d2cb04b5850ab042255 to your computer and use it in GitHub Desktop.
JS: Immutably insert value to an array
/**
* Immutably insert attachments
*
* @example
* insert([null, null, null, null, 5, null], 2, 9)
* [null, null, 9, null, null, 5, null]
*
* @param {array} array
* @param {number} index
* @param {mixed} value
* @return {array}
*/
export default function insert(array, index, value) {
const left = array.slice(0, index);
const right = array.slice(index);
return [...left, value, ...right];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment