Skip to content

Instantly share code, notes, and snippets.

@lski
Last active April 28, 2022 09:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lski/0eae0d2738831b6b0ec2b88a8a603952 to your computer and use it in GitHub Desktop.
Save lski/0eae0d2738831b6b0ec2b88a8a603952 to your computer and use it in GitHub Desktop.
Array.reduce polyfill created by MDN, made available to use with NPM
// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(callback /*, initialValue*/) {
'use strict';
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;
};
}
Array.prototype.reduce||(Array.prototype.reduce=function(r){"use strict";if(null==this)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof r)throw new TypeError(r+" is not a function");var e,t=Object(this),n=t.length>>>0,o=0;if(2==arguments.length)e=arguments[1];else{for(;n>o&&!(o in t);)o++;if(o>=n)throw new TypeError("Reduce of empty array with no initial value");e=t[o++]}for(;n>o;o++)o in t&&(e=r(e,t[o],o,t));return e});
{
"name": "array-reduce-polyfill",
"version": "1.0.0",
"main": "array.reduce-polyfill.min.js"
}
@dev-1995
Copy link

why are we checking again (k in t) in last for loop ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment