Cycymomo
1/30/2014 - 5:46 PM

insertAt : Array.prototype & String.prototype.

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']