From f40d03290be4bcf8907269ad9105a3f2cee94a97 Mon Sep 17 00:00:00 2001 From: Bernavschi Natalia Date: Tue, 8 Jul 2025 10:21:26 +0300 Subject: [PATCH] add task solution for qa_array-method-reduce --- src/reduce.js | 10 ++++++++-- src/reduce.test.js | 49 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/src/reduce.js b/src/reduce.js index 38be21c..8e0b3dc 100644 --- a/src/reduce.js +++ b/src/reduce.js @@ -7,12 +7,18 @@ * @returns {*} */ function reduce(callback, startValue) { - let prev = startValue; + let prev; let startIndex = 0; if (arguments.length < 2) { - startIndex = 1; + if (this.length === 0) { + throw new TypeError('Reduce of empty array with no initial value'); + } + prev = this[0]; + startIndex = 1; + } else { + prev = startValue; } for (let i = startIndex; i < this.length; i++) { diff --git a/src/reduce.test.js b/src/reduce.test.js index 47a892f..651ce19 100644 --- a/src/reduce.test.js +++ b/src/reduce.test.js @@ -1,3 +1,4 @@ +/* eslint-disable max-len */ 'use strict'; const { reduce } = require('./reduce'); @@ -11,9 +12,53 @@ describe('reduce', () => { delete Array.prototype.reduce2; }); - it('should ', () => { + it('should sum up numbers with initial value', () => { + const result = [1, 2, 3, 4].reduce2((acc, val) => acc + val, 10); + expect(result).toBe(20); }); - // Add tests here + it('should sum up numbers without initial value', () => { + const result = [1, 2, 3, 4].reduce2((acc, val) => acc + val); + + expect(result).toBe(10); + }); + + it('should concatenate strings', () => { + const result = ['a', 'b', 'c'].reduce2((acc, val) => acc + val, ''); + + expect(result).toBe('abc'); + }); + + it('should multiply numbers without initial value', () => { + const result = [2, 3, 4].reduce2((acc, val) => acc * val); + + expect(result).toBe(24); + }); + + it('should use array index and array as arguments', () => { + const spy = jest.fn((acc, val, i, array) => acc + val); + const arr = [1, 2, 3]; + + arr.reduce2(spy, 0); + expect(spy).toHaveBeenCalledWith(0, 1, 0, arr); + expect(spy).toHaveBeenCalledWith(1, 2, 1, arr); + expect(spy).toHaveBeenCalledWith(3, 3, 2, arr); + }); + + it('should work on array with single element and no initial value', () => { + const result = [42].reduce2((acc, val) => acc + val); + + expect(result).toBe(42); + }); + + it('should throw error on empty array with no initial value', () => { + expect(() => [].reduce2((acc, val) => acc + val)).toThrow(); + }); + + it('should return initial value on empty array if initial value provided', () => { + const result = [].reduce2((acc, val) => acc + val, 100); + + expect(result).toBe(100); + }); });