Skip to content

Commit f9bedeb

Browse files
authored
Merge pull request #4 from ClayWangT/ClayWangT-patch-1
[fix] sandbox reducer behavior
2 parents 464cad3 + 158dbee commit f9bedeb

1 file changed

Lines changed: 17 additions & 10 deletions

File tree

src/sandbox.js

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,25 +70,32 @@ export function wrapProtoMethod(executor) {
7070
};
7171

7272
Array.prototype.reduce = function reduce(reducer, init) {
73+
const hasInit = arguments.length > 1;
7374
if (typeof reducer === 'function' && funcToString.call(reducer).indexOf(FUNC_MARK) !== -1) {
74-
return executor((function* (array) {
75-
let result = init;
76-
for (let i = 0; i < array.length; i++) result = yield reducer(result, array[i], i, array);
75+
return executor(function* (array) {
76+
let result = hasInit ? init : array[0];
77+
for (let i = hasInit ? 0 : 1; i < array.length; i++) result = yield reducer(result, array[i], i, array);
7778
return result;
78-
})(this));
79+
}(this));
7980
}
80-
return oriArrayReduce.call(this, reducer, init);
81+
if (hasInit) return oriArrayReduce.call(this, reducer, init);
82+
return oriArrayReduce.call(this, reducer);
8183
};
8284

8385
Array.prototype.reduceRight = function reduceRight(reducer, init) {
86+
const hasInit = arguments.length > 1;
8487
if (typeof reducer === 'function' && funcToString.call(reducer).indexOf(FUNC_MARK) !== -1) {
85-
return executor((function* (array) {
86-
let result = init;
87-
for (let i = array.length - 1; i !== -1; i--) result = yield reducer(result, array[i], i, array);
88+
return executor(function* (array) {
89+
let result = hasInit? init : array[array.length - 1];;
90+
91+
for (let i = hasInit ? array.length - 1: array.length - 2; i !== -1; i--) result = yield reducer(result, array[i], i, array);
92+
8893
return result;
89-
})(this));
94+
}(this));
9095
}
91-
return oriArrayReduceRight.call(this, reducer, init);
96+
97+
if(hasInit) return oriArrayReduceRight.call(this, reducer, init);
98+
return oriArrayReduceRight.call(this, reducer);
9299
};
93100

94101
Array.prototype.every = function every(predicate, thisArg) {

0 commit comments

Comments
 (0)