Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(groupBy): return Partial Record #45

Merged
merged 5 commits into from
Jun 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions test/groupBy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { expectType } from 'tsd';
import { groupBy, __ } from '../es';

// returns optional arrays for the groups

const byGrade = groupBy((student: { score: number; name: string }) => {
const score = student.score;
return score < 65 ? 'F' : score < 70 ? 'D' : score < 80 ? 'C' : score < 90 ? 'B' : 'A';
});
const students = [
{ name: 'Abby', score: 84 },
{ name: 'Eddy', score: 58 },
{ name: 'Jack', score: 69 }
];

const grouped = byGrade(students);
expectType<{ score: number; name: string }[] | undefined>(grouped.C);
(grouped.C ?? []).length;
// @ts-expect-error
grouped.C.length;

// accepts a placeholder and later specifying the grouping function

const byGrade2 = groupBy(__, students);
const grouped2 = byGrade2((student: { score: number; name: string }) => {
const score = student.score;
return score < 65 ? 'F' : score < 70 ? 'D' : score < 80 ? 'C' : score < 90 ? 'B' : 'A';
});
expectType<{ score: number; name: string }[] | undefined>(grouped2.C);
7 changes: 5 additions & 2 deletions types/groupBy.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
export function groupBy<T, K extends string = string>(fn: (a: T) => K): (list: readonly T[]) => Record<K, T[]>;
export function groupBy<T, K extends string = string>(fn: (a: T) => K, list: readonly T[]): Record<K, T[]>;
import { Placeholder } from './util/tools';

export function groupBy<T, K extends string = string>(fn: (a: T) => K): (list: readonly T[]) => Partial<Record<K, T[]>>;
export function groupBy<T>(__: Placeholder, list: readonly T[]): <K extends string = string>(fn: (a: T) => K) => Partial<Record<K, T[]>>;
export function groupBy<T, K extends string = string>(fn: (a: T) => K, list: readonly T[]): Partial<Record<K, T[]>>;