Skip to content

Instantly share code, notes, and snippets.

@jiggzson
Created March 12, 2016 22:08
Show Gist options
  • Save jiggzson/8b2ca3ea582d22727526 to your computer and use it in GitHub Desktop.
Save jiggzson/8b2ca3ea582d22727526 to your computer and use it in GitHub Desktop.
/**
* Inserts an object into an array at a given index or recursively adds items if an array is given.
* When inserting another array, passing in false for unpackArray will result in the array being inserted
* rather than its items.
* @param {Array} arr - The target array
* @param {Array} item - The item being inserted
* @param {Number} index - Where to place the item
* @param {boolean} unpackArray - Will insert the array instead of adding its items
*/
insertArray = Utils.insertArray = function( arr, item, index, unpackArray ) {
unpackArray = unpackArray === false ? unpackArray : true;
if( isArray( item ) && unpackArray ) {
for( var i=0; i<=item.length+1; i++ ){
insertArray( arr, item.pop(), index );
}
}
else if( typeof index === 'undefined ') {
arr.push( item );
}
else{
arr.splice( index, 0, item );
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment