Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Last active December 10, 2015 04:18
Show Gist options
  • Save XoseLluis/4379974 to your computer and use it in GitHub Desktop.
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
//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;
}
@XoseLluis
Copy link
Author

I got confused and created this same script previously as Anonymous.

@XoseLluis
Copy link
Author

replaced Array.prototype.slice with [].slice

@dcarral
Copy link

dcarral commented May 12, 2014

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