Created
March 5, 2011 19:40
-
-
Save eriwen/856652 to your computer and use it in GitHub Desktop.
Playing around with implementing ES5 Array extras
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
/** | |
* Attach function to Array.prototype, with the given implementation. | |
*/ | |
function augmentArrayPrototypeWith(func, impl) { | |
if (typeof Array.prototype[func] !== 'function') { | |
Array.prototype[func] = function() { | |
return impl.apply(this, arguments); | |
}; | |
} | |
} | |
augmentArrayPrototypeWith('indexOf', function(obj/*, fromIndex*/) { | |
var len = checkArray.apply(this); | |
var k = normalizeFromIndex.call(this, 0, arguments); | |
for (; k < len; k++) { | |
if (this[k] === obj) { | |
return k; | |
} | |
} | |
return -1; | |
}); | |
augmentArrayPrototypeWith('lastIndexOf', function(obj/*, fromIndex*/) { | |
var len = checkArray.apply(this); | |
var k = normalizeFromIndex.call(this, len, arguments); | |
for(; k >= 0; k--) { | |
if (this[k] === obj) { | |
return k; | |
} | |
} | |
return -1; | |
}); | |
function checkArray() { | |
if (this && this.constructor !== Array) { | |
throw new TypeError(); | |
} | |
return (this.length !== 0 ? this.length : -1); | |
} | |
function normalizeFromIndex(other, args) { | |
var fromIndex = other; | |
if (args.length > 1) { | |
fromIndex = Number(args[1]); | |
if (fromIndex !== fromIndex) { //NaN check | |
fromIndex = other; | |
} else if (fromIndex !== 0 && fromIndex !== (1 / 0) && fromIndex !== -(1 / 0)) { | |
fromIndex = (fromIndex > 0 || -1) * Math.floor(Math.abs(fromIndex)); | |
} | |
} | |
return fromIndex >= 0 ? fromIndex : other; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment