Last active
April 28, 2022 09:16
-
-
Save lski/0eae0d2738831b6b0ec2b88a8a603952 to your computer and use it in GitHub Desktop.
Array.reduce polyfill created by MDN, made available to use with NPM
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
// 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; | |
}; | |
} |
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.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}); |
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
{ | |
"name": "array-reduce-polyfill", | |
"version": "1.0.0", | |
"main": "array.reduce-polyfill.min.js" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why are we checking again (k in t) in last for loop ?