Skip to content

Commit

Permalink
Fixed reduceWith and reduceRightWith not using the initial value …
Browse files Browse the repository at this point in the history
…when `reduce` was called with more than three arguments
  • Loading branch information
ascartabelli committed Nov 15, 2023
1 parent ccf9f06 commit ce95d4d
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
8 changes: 8 additions & 0 deletions src/array/__tests__/reduceRight.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import identity from "../../core/identity";
import mapValuesWith from "../../object/mapValuesWith";
import reduceRight from "../reduceRight";
import reduceRightWith from "../reduceRightWith";
import subtract from "../../math/subtract";
Expand Down Expand Up @@ -63,6 +64,13 @@ describe("reduceRight / reduceRightWith", () => {
expect(sumMock).toHaveBeenCalledTimes(6);
});

it("should use all the necessary arguments even if reduce is called with more than three arguements", () => {
// causes reduce to be called with five arguments
const f = mapValuesWith(reduceRightWith(sum, 7));

expect(f({ a: [...arr] }).a).toBe(22);
});

it("should build a function throwing an exception if the accumulator isn't a function or is missing", () => {
nonFunctions.forEach(value => {
expect(() => { reduceRight(arr, value, 0); }).toThrow();
Expand Down
8 changes: 8 additions & 0 deletions src/core/__tests__/reduce.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import identity from "../identity";
import mapValuesWith from "../../object/mapValuesWith";
import reduce from "../reduce";
import reduceWith from "../reduceWith";
import subtract from "../../math/subtract";
Expand Down Expand Up @@ -63,6 +64,13 @@ describe("reduce / reduceWith", () => {
expect(sumMock).toHaveBeenCalledTimes(6);
});

it("should use all the necessary arguments even if reduce is called with more than three arguements", () => {
// causes reduce to be called with five arguments
const f = mapValuesWith(reduceWith(sum, 7));

expect(f({ a: [...arr] }).a).toBe(22);
});

it("should build a function throwing an exception if the accumulator isn't a function or is missing", () => {
nonFunctions.forEach(value => {
expect(() => { reduce(arr, value, 0); }).toThrow();
Expand Down
8 changes: 4 additions & 4 deletions src/privates/_makeReducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@ function _makeReducer (step) {
var nCalls;
var result;

if (arguments.length === 3) {
nCalls = len;
result = initialValue;
} else {
if (arguments.length < 3) {
if (len === 0) {
throw new TypeError("Reduce of empty array-like with no initial value");
}

result = arrayLike[idx];
idx += step;
nCalls = len - 1;
} else {
nCalls = len;
result = initialValue;
}

for (; nCalls--; idx += step) {
Expand Down

0 comments on commit ce95d4d

Please sign in to comment.