Skip to content

Instantly share code, notes, and snippets.

@pluma pluma/arrutils.js
Created Feb 19, 2017

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.