Skip to content

Instantly share code, notes, and snippets.

@rflmyk
Last active April 27, 2017 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rflmyk/bb8d54a077a27865f80ae8b9f5f1aeb0 to your computer and use it in GitHub Desktop.
Save rflmyk/bb8d54a077a27865f80ae8b9f5f1aeb0 to your computer and use it in GitHub Desktop.
Polyfills to functional javascript
if (!Array.prototype.filter) {
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;
};
}
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
};
}
if (!Array.prototype.map) {
Array.prototype.map = function(fn) {
var rv = [];
for(var i=0, l=this.length; i<l; i++)
rv.push(fn(this[i]));
return rv;
};
}
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(callback) {
if (this == null) {
throw new TypeError('Array.prototype.reduce called on null or undefined.');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function.');
}
var t = Object(this), len = t.length >>> 0, k = 0, value;
if (arguments.length == 2) {
value = arguments[1];
} else {
while (k < len && !(k in t)) {
k++;
}
if (k >= len) {
throw new TypeError('Reduce of empty array with no initial value.');
}
value = t[k++];
}
for (; k < len; k++) {
if (k in t) {
value = callback(value, t[k], k, t);
}
}
return value;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment