Created
February 19, 2012 16:41
-
-
Save arnehormann/1864575 to your computer and use it in GitHub Desktop.
Splice an array - with undo
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
function spliceRevertable() { | |
var self = this | |
, revertArray = [arguments[0], arguments.length - 2] | |
, result = revertArray.splice.apply(this, arguments) | |
, revertArguments = revertArray.concat(revertArray.slice.call(arguments, 2)) | |
result.revert = funtion() { | |
return revertArguments.splice.apply(self, revertArguments) | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Splice - The ultimate array function
Array.splice
is an incredibly powerful function. It can be used for insertion, deletion and updates. Honestly, it provides all opertions you'll ever need when you want to modify an Array.Here's the signature:
[].splice(index, numberRemoved, ...elements to be inserted...)
.It returns an array containing the removed elements and modifies the array it's called on.
So... for operations on one element:
array.splice(insertionIndex, 0, newElement)
array.splice(0, 0, newElement)
array.splice(array.length, 0, newElement)
array.splice(removalIndex, 1)
array.splice(array.length - 1, 1)
array.splice(replacementIndex, 1, newElement)
You can even clear the whole array with
array.splice(0, array.length)
.With splice as your only method for modifications, you can use
spliceRevertable
like this:spliceRevertable.call(array, regular splice arguments)
(or - if you really want to be able to use it on every Array -Array.spliceRevertable = spliceRevertable;
).When you call
revert()
on the result, it will undo the operation leading to the result and the change and return the change.I use this for optimistic UI updates. But you have to be carefull: only the last call can cleanly be reverted - or the calls have to be reverted in the reverse order of original calls. Otherwise, the first argument (index) will mess up your array.