Skip to content

Instantly share code, notes, and snippets.

@beaucharman
Last active February 22, 2019 21:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beaucharman/d0cfc5eec892b4961a57573599889528 to your computer and use it in GitHub Desktop.
Save beaucharman/d0cfc5eec892b4961a57573599889528 to your computer and use it in GitHub Desktop.
An ES6 / pure function implementation of the JS splice method that returns an object of the new array and the removed elements
function safeSplice(array, start, deleteCount, ...replace) {
const removed = array.splice(start, deleteCount, ...replace)
return {
array: array,
removed: removed,
}
}
/** usage
const array = [1, 2, 3, 4, 5, 6]
const { array: newArray, removed } = safeSplice(array, 2, 2, 'foo', 'bar')
console.log(newArray, removed)
*/
@filippoitaliano
Copy link

This function is an 'inpure function', isn't it? It modifies the array passed as parameter.

@sergiubologa
Copy link

Yes, it's not really a pure function because it modifies the array.

@YuCJ
Copy link

YuCJ commented Apr 19, 2018

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