ts-02-groupby
1.000
Proposed solution
```ts
export function groupBy<T, K extends string | number>(
items: T[],
keyFn: (item: T) => K,
): Record<K, T[]> {
const result: Partial<Record<K, T[]>> = {};
for (const item of items) {
const key = keyFn(item);
if (!result[key]) {
result[key] = [];
}
result[key]?.push(item);
}
return result as Record<K, T[]>;
}
```Test output (stdout)
TAP version 13 # Subtest: groups by string key, preserving order ok 1 - groups by string key, preserving order --- duration_ms: 0.584773 type: 'test' ... # Subtest: empty input yields empty record ok 2 - empty input yields empty record --- duration_ms: 0.06379 type: 'test' ... # Subtest: groups by numeric key ok 3 - groups by numeric key --- duration_ms: 0.065971 type: 'test' ... # Subtest: groups objects by a property ok 4 - groups objects by a property --- duration_ms: 0.07055 type: 'test' ... # Subtest: single group when keyFn is constant ok 5 - single group when keyFn is constant --- duration_ms: 0.056781 type: 'test' ... # Subtest: does not mutate the input array ok 6 - does not mutate the input array --- duration_ms: 0.04701 type: 'test' ... 1..6 # tests 6 # suites 0 # pass 6 # fail 0 # cancelled 0 # skipped 0 # todo 0 # duration_ms 76.610561
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.