Skip to content

Commit 8c8a827

Browse files
authored
Added reduce.js (New pull request) (#8)
Added reduce.js (New pull request)
2 parents 177b4c3 + db40eef commit 8c8a827

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-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+
}

index.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,43 @@ if (!Array.from) {
7878
}());
7979
}
8080

81+
//reduce.js
82+
/*
83+
Source of the polyfill:
84+
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Polyfill
85+
86+
*/
87+
88+
if(!Array.prototype.reduce){
89+
90+
Array.prototype.reduce = function(callback) {
91+
'use strict';
92+
if (this == null) {
93+
throw new TypeError('Array.prototype.reduce called on null or undefined');
94+
}
95+
if (typeof callback !== 'function') {
96+
throw new TypeError(callback + ' is not a function');
97+
}
98+
var t = Object(this), len = t.length >>> 0, k = 0, value;
99+
if (arguments.length == 2) {
100+
value = arguments[1];
101+
} else {
102+
while (k < len && !(k in t)) {
103+
k++;
104+
}
105+
if (k >= len) {
106+
throw new TypeError('Reduce of empty array with no initial value');
107+
}
108+
value = t[k++];
109+
}
110+
for (; k < len; k++) {
111+
if (k in t) {
112+
value = callback(value, t[k], k, t);
113+
}
114+
}
115+
return value;
116+
};
117+
}
81118
//assign.js
82119
/**
83120
* https://gist.github.com/WebReflection/10404826

0 commit comments

Comments
 (0)