Created
October 22, 2014 23:24
-
-
Save tapmodo/6cf4b1a8ec991e3f74f2 to your computer and use it in GitHub Desktop.
Array.filter and Array.map Javascript Polyfills
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
// Array.map polyfill | |
if (Array.prototype.map === undefined) { | |
Array.prototype.map = function(fn) { | |
var rv = []; | |
for(var i=0, l=this.length; i<l; i++) | |
rv.push(fn(this[i])); | |
return rv; | |
}; | |
} | |
// Array.filter polyfill | |
if (Array.prototype.filter === undefined) { | |
Array.prototype.filter = function(fn) { | |
var rv = []; | |
for(var i=0, l=this.length; i<l; i++) | |
if (fn(this[i])) rv.push(this[i]); | |
return rv; | |
}; | |
} | |
I agree with @AjayPoshak.
for comparaison here is the map polyfill provided on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This solution is very risky.
In both polyfills, you are not even doing a sanity check for function supplied as the argument.
And please check the proper signature of filter method.