Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Shopping Cart

Object-Oriented Programmingmedium

Course · Section 14: Object-Oriented Programming (OOP) With JavaScript · Lecture 226: ES6 Classes

Model a shopping cart. Implement `ShoppingCart`: - `addItem(name, price, qty)` adds a line item. - `removeItem(name)` removes all lines with that name. - `total()` returns the sum of price times quantity. - `count()` returns the total quantity of items.

Examples

Input: addItem('apple',2,3), addItem('bread',3,1), total(), removeItem('apple'), total(), count()
Output: [9, 3, 1]
Total is 2*3 + 3*1 = 9; after removing apple it is 3 with one item left.

Sample tests

Input: add, total, remove, total, count
Output: [9,3,1]
Input: empty cart
Output: [0,0]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Forgetting to multiply price by quantity in the total.
Approach & explanation (try first)

An array of line items with reduce-based aggregates models cart totals and counts cleanly.

Loading...
⌘/Ctrl + Enter

Run your code to see results.