Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/reduce.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
* @returns {*}
*/
function reduce(callback, startValue) {
if (this.length === 0 && arguments.length < 2) {
throw new TypeError('Reduce of empty array with no initial value');
}

let prev = startValue;
let startIndex = 0;

Expand Down
63 changes: 56 additions & 7 deletions src/reduce.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,65 @@

const { reduce } = require('./reduce');

describe('reduce', () => {
beforeAll(() => {
Array.prototype.reduce2 = reduce; // eslint-disable-line
describe('Custom reduce method', () => {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test suite is missing a critical check for a core behavior of reduce. When called on an empty array without an initial value, the native method throws a TypeError. Please add a test case to verify this behavior. You can use Jest's toThrow() matcher for this.

let numbers;

beforeEach(() => {
numbers = [1, 2, 3, 4];
});

it('should sum all numbers with initial value', () => {
const result = reduce.call(numbers, (acc, num) => acc + num, 0);

expect(result).toBe(10);
});

it('should sum all numbers without initial value', () => {
const result = reduce.call(numbers, (acc, num) => acc + num);

expect(result).toBe(10);
});

it('should multiply all numbers', () => {
const result = reduce.call(numbers, (acc, num) => acc * num, 1);

expect(result).toBe(24);
});

afterAll(() => {
delete Array.prototype.reduce2;
it('should concatenate strings', () => {
const words = ['Hello', ' ', 'World'];

const result = reduce.call(words, (acc, word) => acc + word, '');

expect(result).toBe('Hello World');
});

it('should ', () => {});
it('should return initial value for empty array', () => {
const result = reduce.call([], (acc, num) => acc + num, 100);

// Add tests here
expect(result).toBe(100);
});

it('should throw TypeError for empty array without initial value', () => {
expect(() => {
reduce.call([], (acc, num) => acc + num);
}).toThrow(TypeError);
});

it('should call callback correct number of times', () => {
const callback = jest.fn((acc, num) => acc + num);

reduce.call(numbers, callback, 0);

expect(callback).toHaveBeenCalledTimes(4);
});

it('should pass correct arguments to callback', () => {
const callback = jest.fn((acc, num) => acc + num);

reduce.call(numbers, callback, 0);

expect(callback).toHaveBeenNthCalledWith(1, 0, 1, 0, numbers);
expect(callback).toHaveBeenNthCalledWith(2, 1, 2, 1, numbers);
});
});
Loading