Code of the Day
AdvancedTooling & Types

Lab: robust code

Write functions that handle the awkward inputs — the difference between code and reliable code.

Lab · optionalJavaScript / TSAdvanced16 min
Recommended first
By the end of this lesson you will be able to:
  • Handle invalid and edge-case input deliberately
  • Validate before you trust a value
  • Build a reusable data-shaping helper

Optional lab. Reliable code is mostly about the inputs you didn't hope for. These checks include the awkward cases on purpose — make them all green.

Checkpoint 1 — safe integer parsing

User input is text and often junk. Write safeParseInt(text, fallback) that returns the integer value of text, or fallback when text isn't a valid integer. Watch the traps: "3.5" isn't an integer, and a blank string is not a zero.

Parse an integer safelyJavaScript

Write safeParseInt(text, fallback): return the integer value of text, or fallback if text is not a valid integer. Blank/whitespace is invalid; decimals like "3.5" are invalid.

safeParseInt('42', -1)42safeParseInt('', -1)-1

The blank-string trap: Number('') is 0, which is an integer — so a naive check returns 0 instead of the fallback. Guard text.trim() === '' first, then use Number(text) with Number.isInteger(...).

Checkpoint 2 — groupBy

Write a reusable groupBy(items, keyFn) that returns an object mapping each key (from keyFn(item)) to the array of items with that key — a workhorse helper you'll reach for constantly.

Group items by a keyJavaScript

Write groupBy(items, keyFn) returning an object: each key produced by keyFn maps to an array of the items with that key, in order. groupBy([], fn) is {}.

groupBy([1,2,3,4], n => n%2 ? 'odd':'even'){ odd:[1,3], even:[2,4] }

The pattern: for each item compute const k = keyFn(item), create result[k] = result[k] || [], then result[k].push(item). That || [] is the "first time I've seen this key" guard — the same idea as Python's dict.get(k, []).

Done?

All green? You handled the inputs that break naive code and built a helper worth keeping. That instinct — what's the awkward case? — is what separates code that works in the demo from code that survives production.

Finished reading? Mark it complete to track your progress.

On this page