What you are practising: converting a working but unsafe utility into a generic function the compiler can reason about.
Accept the assignment, clone your repository, then install the tooling once:
npm install- Open a terminal in the
exercise/folder. - Rename the starter:
mv group-by.js group-by.ts. - Work through what the compiler surfaces.
- Compile with a bare
npx tsc. Notnpx tsc group-by.ts: a filename argument makestscskiptsconfig.json, so the strict settings would not apply. - Run the output:
node group-by.js.
The file contains groupBy, a utility that groups items in an array by a key. The JavaScript version works, but it has no type safety and will happily do nonsense if you pass it the wrong inputs.
- Rename
group-by.jstogroup-by.ts. - Convert the function to a generic that takes:
- an array of items of type
T - a key-selector function that returns a
stringgiven aT
- an array of items of type
- Return a
Record<string, T[]>(a lookup of group name to items). - Add a small test block that groups an array of learners by the first letter of their name.
- Compile with
npx tscand run it withnode group-by.js.
The starter ends with two commented-out nonsense calls. Once your conversion is done, uncomment them and check the compiler rejects both.
Keep the exported function name (groupBy) — the autograder imports it by name.
- Make the key selector generic too. What happens if you let it return any type, not just
string? What type would the returnedRecordneed to be? - Add a second function,
partition, which splits an array in two based on a predicate. Type it generically. - Does your
groupByhandle an empty array? What about an array with one item?
npx tsc completes with no errors, the nonsense calls fail to compile when uncommented, node group-by.js prints your groupings (including the learners test block), and your work is committed and pushed.
Every push runs two GitHub Actions checks:
- Type check — runs
npx tscon your exercise under the strict settings, once you have renamed the starter to.ts. - Autograding — runs an automated test suite (Vitest) against your functions and reports a functionality score, plus an automated code-quality review.