Skip to content

Instantly share code, notes, and snippets.

@rgdelato
Last active April 9, 2018 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rgdelato/1f94a7a86006b307a81e8a76dbb91055 to your computer and use it in GitHub Desktop.
Save rgdelato/1f94a7a86006b307a81e8a76dbb91055 to your computer and use it in GitHub Desktop.
ES5 Array methods as applied to Object.prototype (map and filter are currently incorrect implementations)
// ES5 Array methods
// New methods added: Array.isArray, indexOf, lastIndexOf, every, some,
// forEach, map, filter, reduce, reduceRight
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
// Array.prototype.reduce(function (previousValue, currentValue, currentIndex, array), initialValue)
if (!Object.prototype.reduce) {
Object.prototype.reduce = function (callback, initialValue) {
var _this = this;
return Object.keys(_this).reduce(function (acc, key, i) {
return callback(acc, _this[key], key, _this);
}, initialValue);
};
}
// Array.prototype.forEach(function (currentValue, index, array), thisArg)
if (!Object.prototype.forEach) {
Object.prototype.forEach = function (callback, thisBinding) {
var _this = this;
Object.keys(_this).forEach(function (key, i) {
callback.apply(thisBinding, [_this[key], key, _this]);
});
return undefined;
};
}
// Array.prototype.map(function (currentValue, index, array), thisArg)
if (!Object.prototype.map) {
Object.prototype.map = function (callback, thisBinding) {
var _this = this;
return Object.keys(_this).map(function (key, i) {
return callback.apply(thisBinding, [_this[key], key, _this]);
});
}
}
// Array.prototype.filter(function (currentValue, index, array), thisArg)
if (!Object.prototype.filter) {
Object.prototype.filter = function (callback, thisBinding) {
var _this = this;
return Object.keys(_this).filter(function (key, i) {
return callback.apply(thisBinding, [_this[key], key, _this]);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment