Skip to content

Commit

Permalink
fix: groupBy types
Browse files Browse the repository at this point in the history
  • Loading branch information
Thanga-Ganapathy committed Feb 12, 2024
1 parent 2f66dc0 commit 2942e8b
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/slimy-countries-look.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@opentf/utils": minor
---

Fixed groupBy types.
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,29 @@ describe('Array', () => {
v % 2 === 0 ? 'Even' : 'Odd'
)
).toEqual({ Even: [2, 4, 6, 8], Odd: [1, 3, 5, 7, 9] });

expect(groupBy(['one', 'two', 'three'], 'length')).toEqual({
3: ['one', 'two'],
5: ['three'],
});

const inventory = [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'cherries', type: 'fruit', quantity: 5 },
{ name: 'fish', type: 'meat', quantity: 22 },
];
expect(groupBy(inventory, ({ type }) => type)).toEqual({
vegetables: [{ name: 'asparagus', type: 'vegetables', quantity: 5 }],
fruit: [
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 5 },
],
meat: [
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'fish', type: 'meat', quantity: 22 },
],
});
});
});
13 changes: 8 additions & 5 deletions packages/utils/src/array/groupBy.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
export type GroupKey = (a: unknown) => string | string;
export type GroupKey<T> = ((a: T) => string) | string;

export default function groupBy(arr: unknown[], key: GroupKey) {
return arr.reduce((acc: Record<string, unknown>, obj) => {
export default function groupBy<T>(
arr: T[],
key: GroupKey<T>
): Record<string, T[]> {
return arr.reduce((acc: Record<string, T[]>, obj: T) => {
const k =
typeof key === 'function' ? key(obj) : (obj as Iterable<unknown>)[key];
typeof key === 'function' ? key(obj) : (obj[key as keyof T] as string);
const curGroup = acc[k] ?? [];
return { ...acc, [k]: [...(curGroup as unknown[]), obj] };
return { ...acc, [k]: [...curGroup, obj] };
}, {});
}

0 comments on commit 2942e8b

Please sign in to comment.