diff --git a/packages/collection/__tests__/collection.test.ts b/packages/collection/__tests__/collection.test.ts index a052a391f021..fc069376b926 100644 --- a/packages/collection/__tests__/collection.test.ts +++ b/packages/collection/__tests__/collection.test.ts @@ -700,12 +700,17 @@ describe('reduce() tests', () => { test('reduce collection into a single value with initial value', () => { const sum = coll.reduce((a, x) => a + x, 0); - expect(sum).toStrictEqual(6); + expect(sum).toStrictEqual(6); }); test('reduce collection into a single value without initial value', () => { - const sum = coll.reduce((a, x) => a + x); - expect(sum).toStrictEqual(6); + const sum = coll.reduce((a, x) => a + x); + expect(sum).toStrictEqual(6); + }); + + test('reduce empty collection with initial value', () => { + const coll = createCollection(); + expect(coll.reduce((a, x) => a + x, 0)).toStrictEqual(0); }); test('reduce empty collection without initial value', () => { diff --git a/packages/collection/src/collection.ts b/packages/collection/src/collection.ts index 5a8a8ead7fb9..0547ebb81006 100644 --- a/packages/collection/src/collection.ts +++ b/packages/collection/src/collection.ts @@ -514,30 +514,20 @@ export class Collection extends Map { * collection.reduce((acc, guild) => acc + guild.memberCount, 0); * ``` */ - public reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T { + public reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T { if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); let accumulator!: T; - if (initialValue !== undefined) { + const iterator = this.entries(); + if (initialValue === undefined) { + if (this.size === 0) throw new TypeError('Reduce of empty collection with no initial value'); + accumulator = iterator.next().value[1]; + } else { accumulator = initialValue; - for (const [key, val] of this) accumulator = fn(accumulator, val, key, this); - return accumulator; } - let first = true; - for (const [key, val] of this) { - if (first) { - accumulator = val as unknown as T; - first = false; - continue; - } - - accumulator = fn(accumulator, val, key, this); - } - - // No items iterated. - if (first) { - throw new TypeError('Reduce of empty collection with no initial value'); + for (const [key, value] of iterator) { + accumulator = fn(accumulator, value, key, this); } return accumulator;