Codington
0 of 6 problems solved0%

Total Prices from Unknown

Accept unknown and safely work toward a number. If the input is an array of objects with a numeric price, sum the prices. Otherwise return 0.

Check with Array.isArray. Then, for each item, make sure it is an object, not null, has a price key, and that price is a number.

function total(xs: unknown) { if (!Array.isArray(xs)) return 0; let t = 0; for (const it of xs) { if (typeof it === "object" && it && "price" in it) { const p = (it as { price?: unknown }).price; if (typeof p === "number") t += p; } } return t; }

Your Task

Implement a function that totals prices when input is an array of price objects.

  • Write function totalPrices(input: unknown): number.
  • If input is an array of { price: number }, return the sum of price.
  • Ignore items without a numeric price.
  • Return 0 if input is not an array or is empty.
  • Do not mutate inputs.