Skip to lesson
Exit
Applied Coding & Editor Primitives1 / 2

1 min lesson

Small, well-typed helpers

Talk through the example in "Small, well-typed helpers", then name the result it is meant to produce.

Step 1 of 2

Small, well-typed helpersdon't any your way out

Reaching for any to escape a type error reads as a tell - the interviewer sees someone fighting the compiler instead of using it. Write a typed helper instead. A clean groupBy is the single most reused shape in these problems, so have it in muscle memory.

Generic, typed, reusable - the workhorse for dedup and bucketing problems.ts
function groupBy<T, K>(items: T[], keyOf: (item: T) => K): Map<K, T[]> {
  const out = new Map<K, T[]>();
  for (const item of items) {
    const k = keyOf(item);
    const bucket = out.get(k);
    if (bucket) bucket.push(item);
    else out.set(k, [item]);
  }
  return out;
}

// findDuplicates becomes two groupBy calls: by size, then by hash.
const bySize = groupBy(files, (f) => f.bytes.length);