feat: override groupBy to return Collection (#10791)

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Danial Raza
2025-03-05 21:19:20 +01:00
committed by GitHub
parent b7e334e74a
commit e273afbb93
2 changed files with 37 additions and 0 deletions

View File

@@ -944,6 +944,29 @@ describe('union() tests', () => {
});
});
describe('groupBy() tests', () => {
test('returns a collection of grouped items', () => {
const items = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 20 },
{ name: 'Charlie', age: 30 },
];
expect<Collection<number, typeof items>>(Collection.groupBy(items, (item) => item.age)).toStrictEqual(
new Collection<number, typeof items>([
[
20,
[
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 20 },
],
],
[30, [{ name: 'Charlie', age: 30 }]],
]),
);
});
});
describe('toReversed() tests', () => {
test('reverses a collection', () => {
const coll = createTestCollection();
@@ -1152,5 +1175,8 @@ describe('subclassing tests', () => {
test('Collection.combineEntries()', () => {
expect(DerivedCollection.combineEntries([], Object)).toBeInstanceOf(DerivedCollection);
});
test('Collection.groupBy()', () => {
expect(DerivedCollection.groupBy([], Object)).toBeInstanceOf(DerivedCollection);
});
});
});

View File

@@ -1088,6 +1088,17 @@ export class Collection<Key, Value> extends Map<Key, Value> {
return coll;
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/groupBy | Map.groupBy()}
* but returns a Collection instead of a Map.
*/
public static override groupBy<Key, Item>(
items: Iterable<Item>,
keySelector: (item: Item, index: number) => Key,
): Collection<Key, Item[]> {
return new this[Symbol.species]<Key, Item[]>(Map.groupBy(items, keySelector));
}
/**
* @internal
*/