Created
February 19, 2017 12:41
-
-
Save pluma/8c45793b14f92b308ce3e6b0a5571ccf to your computer and use it in GitHub Desktop.
ES6 non-mutating array manipulation helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}, []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bonus: