diff --git a/src/reduce.js b/src/reduce.js index 38be21c..3bd3b9b 100644 --- a/src/reduce.js +++ b/src/reduce.js @@ -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; diff --git a/src/reduce.test.js b/src/reduce.test.js index c3331e7..c232ca2 100644 --- a/src/reduce.test.js +++ b/src/reduce.test.js @@ -2,16 +2,65 @@ const { reduce } = require('./reduce'); -describe('reduce', () => { - beforeAll(() => { - Array.prototype.reduce2 = reduce; // eslint-disable-line +describe('Custom reduce method', () => { + 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); + }); });