Přejít k hlavnímu obsahu
← ⚡ JavaScript & the browser·Modul C5 · Lekce 10
ÚkolRefactor process(input) per the theory. Define @typedef Input as (number | string | number[]). Narrow with typeof and Array.isArray. Throw TypeError naming the unsupported type for unknown input. Log process(5), process("hi"), process([1,2,3]). Then in try/catch log the error message from process(true).

Capstone: refactor a tangled function with types

250 XP14 min
Teorie

What you'll fix

The starter has a single function process(input) that handles three different kinds of input:

  • number — return doubled
  • string — return uppercased
  • array of numbers — return sum

It has no types, no narrowing, no validation. Anything that goes in might explode.

Your job

Apply every C5 idea in one pass:

  1. @typedef for the union type the function actually accepts.
  2. JSDoc @param / @returns on the function.
  3. Narrowing for each branch — typeof, Array.isArray.
  4. A clear throw for the unknown-input branch (with the type info in the message).

You'll go from "barely safe spaghetti" to "library-ready function in 12 lines". This is the daily refactor in any non-TS codebase.

🔒

Zaregistruj se a začni programovat

Teorie je otevřená pro každého. Editor, živý náhled a check se odemknou s 7denní zkušební verzí zdarma — karta vyžadována, zrušíš kdykoli.

Registrace — zkušební verze zdarma →

Prvních 10 lekcí v každé trase je zdarma. Karta není potřeba.

← PředchozíDalší lekce →

Jeden tip k Pythonu nebo webu denně — e-mailem

Krátké, ručně psané, žádný spam. Odhlásit jedním klikem.