Last active
December 12, 2015 05:39
-
-
Save termi/4723556 to your computer and use it in GitHub Desktop.
IE8 Array.prototype.splice.apply test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
var _Array_slice_ = Array.prototype['slice']; | |
var _Array_splice_ = Array.prototype.splice; | |
if( Function.prototype.bind === void 0 ) Function.prototype.bind = function (context) { | |
var args = _Array_slice_.call(arguments, 1), self = this; | |
return function (){ return self.apply(context, args.concat(_Array_slice_.call(arguments, 0))); }; | |
}; | |
function makeArray(l) { | |
var a = []; | |
while (l--) { | |
a.unshift(l) | |
} | |
return a | |
} | |
Array.prototype.splice = function(start, deleteCount) { | |
var result | |
, args = _Array_slice_.call(arguments, 2) | |
, addElementsCount = args.length | |
; | |
if(!arguments.length) { | |
return []; | |
} | |
if(start === void 0) { // default | |
start = 0; | |
} | |
if(deleteCount === void 0) { // default | |
deleteCount = this.length - start; | |
} | |
if(addElementsCount > 0) { | |
if(deleteCount <= 0) { | |
if(start == this.length) { // tiny optimisation #1 | |
this.push.apply(this, args); | |
return []; | |
} | |
if(start == 0) { // tiny optimisation #2 | |
this.unshift.apply(this, args); | |
return []; | |
} | |
} | |
// Array.prototype.splice implementation | |
result = _Array_slice_.call(this, start, start + deleteCount);// delete part | |
args.push.apply(args, _Array_slice_.call(this, start + deleteCount, this.length));// right part | |
args.unshift.apply(args, _Array_slice_.call(this, 0, start));// left part | |
// delete all items from this array and replace it to 'left part' + _Array_slice_.call(arguments, 2) + 'right part' | |
args.unshift(0, this.length); | |
_Array_splice_.apply(this, args); | |
return result; | |
} | |
return _Array_splice_.call(this, start, deleteCount); | |
} | |
var array = [] | |
, lengthBefore | |
; | |
array.splice.bind(array, 0, 0).apply(null, makeArray(20)); | |
array.splice.bind(array, 0, 0).apply(null, makeArray(26)); | |
array.splice.apply(array, [5, 0, "XXX"]); // add one element | |
return array.join(",") == "0,1,2,3,4,XXX,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19"; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment