Skip to content

Commit

Permalink
refactor(collection): reduce reduce's code (#9581)
Browse files Browse the repository at this point in the history
* refactor(collection): reduce `reduce`'s code

* fix: resolved bug in tests

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
kyranet and kodiakhq[bot] authored May 18, 2023
1 parent 3535321 commit b85a3f2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 21 deletions.
11 changes: 8 additions & 3 deletions packages/collection/__tests__/collection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number>(sum).toStrictEqual(6);
});

test('reduce collection into a single value without initial value', () => {
const sum = coll.reduce<number>((a, x) => a + x);
expect(sum).toStrictEqual(6);
const sum = coll.reduce((a, x) => a + x);
expect<number>(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', () => {
Expand Down
26 changes: 8 additions & 18 deletions packages/collection/src/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -514,30 +514,20 @@ export class Collection<K, V> extends Map<K, V> {
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
public reduce<T>(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {
public reduce<T = V>(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;
Expand Down

0 comments on commit b85a3f2

Please sign in to comment.