Last active
December 10, 2015 04:18
-
-
Save XoseLluis/4379974 to your computer and use it in GitHub Desktop.
Insert 1 to N items into a JavaScript Array. The original array gets modified and is also returned to enable chaining
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
//inserts 1 to n items into an array arr starting at position pos | |
function insertAt(arr, pos /* , item1, item2, ...itemN */){ | |
switch (arguments.length){ | |
case 0: case 1: case 2: | |
break; | |
case 3: | |
//the default case would work here also, but it's faster it we avoid the extra concat and slice... | |
arr.splice(pos, 0, item); | |
break; | |
default: | |
var args = [pos, 0].concat([].slice.call(arguments, 2)); | |
arr.splice.apply(arr, args); | |
break; | |
} | |
//to enable chaining | |
return arr; | |
} |
Hi Xose: 'arguments[2]' instead of 'item' fixes a little typo at line 8 ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
replaced Array.prototype.slice with [].slice