Skip to content

Instantly share code, notes, and snippets.

@elundmark
Created November 24, 2014 03:46
Show Gist options
  • Save elundmark/ac704677b47165b7ad4f to your computer and use it in GitHub Desktop.
Save elundmark/ac704677b47165b7ad4f to your computer and use it in GitHub Desktop.
Array.prototype.insert
// My brain understands this better than .splice
/* var fruits = ["A","B","C"]; */
if ( typeof Array.insert !== "function" ) {
Array.prototype.insert = function () {
var args = Array.prototype.slice.call(arguments, 0);
// Convert non arrays to array
if ( args.length && !Array.isArray(args[0]) ) args[0] = [args[0]];
// Set default position
if ( args.length === 1 ) args.push(0);
// Make negative pos count from the end
if ( args[1] < 0 ) args[1] = args[1]+this.length+1;
// Now stop invalid numbers
if ( args[1] < 0 ) args[1] = 0;
// Position out of bounds
if ( args[1] > this.length ) args[1] = this.length;
// Warn about usage
if ( args.length !== 2 ) throw new Error("Array.insert takes one or two arguments [array, number]");
// Apply insertion magic
this.splice.apply(this, [args[1], 0].concat(args[0]));
return this;
};
}
/*
document.querySelector("div").innerHTML = fruits;
fruits.insert(["D", "E"], 0);
document.querySelector("p").innerHTML = fruits;
// <!-- <div></div><p></p> -->
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment