Skip to content

Instantly share code, notes, and snippets.

@pluma
Created February 19, 2017 12:41
Show Gist options
  • Save pluma/8c45793b14f92b308ce3e6b0a5571ccf to your computer and use it in GitHub Desktop.
Save pluma/8c45793b14f92b308ce3e6b0a5571ccf to your computer and use it in GitHub Desktop.
ES6 non-mutating array manipulation helpers
export const replace = (arr, index, value) => [
...arr.slice(0, index),
value,
...arr.slice(index + 1)
]
export const insert = (arr, index, value) => [
...arr.slice(0, index),
value,
...arr.slice(index)
]
export const remove = (arr, index) => [
...arr.slice(0, index),
...arr.slice(index + 1)
]
export const shiftUp = (arr, index) => [
...arr.slice(0, index - 1),
arr[index],
...arr.slice(index - 1, index),
...arr.slice(index + 1)
]
export const shiftDown = (arr, index) => [
...arr.slice(0, index),
...arr.slice(index + 1, index + 2),
arr[index],
...arr.slice(index + 2)
]
export const interleave = (arr, sep) => arr.reduce((arr, value) => {
if (arr.length) arr.push(sep)
arr.push(value)
return arr
}, [])
@pluma
Copy link
Author

pluma commented Feb 19, 2017

Bonus:

export const head = (arr) => [arr[0], arr.slice(1)]

export const tail = (arr) => [arr[arr.length - 1], arr.slice(0, arr.length - 1)]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment