Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Cart Summary (Derived, Not Stored)

Derived Statemedium

Course · Section 17: Modern JavaScript Development: Modules, Tooling, and Functional · Lecture 294: Declarative and Functional JavaScript Principles

Totals should be derived from cart items during render, not kept in separate state. Implement `cartSummary(items)` where each item is `{ price, qty }`, returning `{ count, subtotal }` — the total quantity and total price.

Sample tests

Input: cartSummary([{"price":10,"qty":2},{"price":5,"qty":1}])
Output: {"count":3,"subtotal":25}
Input: cartSummary([])
Output: {"count":0,"subtotal":0}

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Storing count/subtotal in their own state risks them drifting out of sync with the cart.
  • Adding only price (not price * qty) ignores the quantity of each line.

Learning resources

  • React: Choosing the State Structure
Approach & explanation (try first)

Derived values are computed from the source of truth on every render, so they cannot fall out of sync. A reduce accumulates the quantity and the per-line price * qty into a single summary object.

Loading...
⌘/Ctrl + Enter

Run your code to see results.