Skip to content

Commit a27cccb

Browse files
authored
Create reduce.js
reduce polyfill
1 parent 18b68c3 commit a27cccb

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Array/reduce.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
3+
Source of the polyfill: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Polyfill
4+
5+
*/
6+
7+
if(!Array.prototype.reduce){
8+
9+
Array.prototype.reduce = function(callback) {
10+
'use strict';
11+
if (this == null) {
12+
throw new TypeError('Array.prototype.reduce called on null or undefined');
13+
}
14+
if (typeof callback !== 'function') {
15+
throw new TypeError(callback + ' is not a function');
16+
}
17+
var t = Object(this), len = t.length >>> 0, k = 0, value;
18+
if (arguments.length == 2) {
19+
value = arguments[1];
20+
} else {
21+
while (k < len && !(k in t)) {
22+
k++;
23+
}
24+
if (k >= len) {
25+
throw new TypeError('Reduce of empty array with no initial value');
26+
}
27+
value = t[k++];
28+
}
29+
for (; k < len; k++) {
30+
if (k in t) {
31+
value = callback(value, t[k], k, t);
32+
}
33+
}
34+
return value;
35+
};
36+
}

0 commit comments

Comments
 (0)