Last active
April 9, 2018 14:15
-
-
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)
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
// 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