Skip to content

Instantly share code, notes, and snippets.

@Cycymomo
Last active August 29, 2015 13:55
Show Gist options
  • Save Cycymomo/8714385 to your computer and use it in GitHub Desktop.
Save Cycymomo/8714385 to your computer and use it in GitHub Desktop.
insertAt : Array.prototype & String.prototype.
// String
String.prototype.insertAt = function( beginSlice, lengthSlice, stringToInsert ) {
lengthSlice = lengthSlice >= 0 ? lengthSlice : -lengthSlice; // ensure abs value. Faster than Math.abs
return this.slice(0, beginSlice) + stringToInsert + this.slice(beginSlice + lengthSlice);
};
var result = "je ton père".insertAt(3, 0, "suis ");
console.log(result); // je suis ton père
var result = "je ton père".insertAt(3, 4, "suis ");
console.log(result); // je suis père
// Array
// Splice alternative (faster on Chrome & IE11 : http://jsperf.com/splice-alternative)
/* array.insert(index, value1, value2, ..., valueN)
Array.prototype.insert = function(index) {
this.splice.apply(this, [index, 0].concat([].slice.call(arguments, 1)));
return this;
};*/
Array.prototype.insertAt = function( beginSlice, lengthSlice, elemToInsert ) {
var arrReturned;
lengthSlice = lengthSlice >= 0 ? lengthSlice : -lengthSlice; // ensure abs value. Faster than Math.abs
arrReturned = this.slice(0, beginSlice);
arrReturned.push(elemToInsert);
return arrReturned.concat(this.slice(beginSlice + lengthSlice));
};
var result = ['je', 'ton', 'père'].insertAt(1, 0, 'suis');
console.log(result); // ['je', 'suis', 'ton', 'père']
var result = ['je', 'ton', 'père'].insertAt(1, 1, 'suis');
console.log(result); // ['je', 'suis', 'père']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment