A shopping cart module

Design a small module with a clear public interface.

What to build

A createCart() function that returns a new, independent cart each time.

Requirements

  • add(name, price) stores an item. Adding the same name again replaces its price.
  • remove(name) removes an item, if it is there.
  • total() returns the sum of the prices.
  • count() returns the number of items.
  • The object must have exactly these four methods, in this order, and no other properties.

Input

Several lines: new, which starts a fresh cart, add NAME PRICE, remove NAME, or show. The input always begins with new.

Output

For each show, a line N items, total T. The last line lists the cart's public names.

Constraints

There are from 2 to 100 commands. Prices are whole numbers from 1 to 100000.

Example

Input:

new
add pen 10
add bag 400
remove pen
show

Output:

1 items, total 400
add,remove,total,count

Why it works

Each call of createCart makes a new Map, so carts cannot affect each other. Because the Map is private, the program can be changed later, say to store quantities, without any change to the code that uses the cart.

Examples

Example 1 · Input
new
add pen 10
add bag 400
remove pen
show
Expected output
1 items, total 400
add,remove,total,count
Example 2 · Input
new
show
Expected output
0 items, total 0
add,remove,total,count

Hints

Hint 1

Use a private Map from each item's name to its price.

Hint 2

Removing an item that is not there should simply do nothing.

Hint 3

total() can add up [...items.values()] with reduce.

Solution

Show one correct solution (try it yourself first)
function createCart() {
  const items = new Map();
  return {
    add(name, price) {
      items.set(name, price);
    },
    remove(name) {
      items.delete(name);
    },
    total() {
      return [...items.values()].reduce((sum, price) => sum + price, 0);
    },
    count() {
      return items.size;
    },
  };
}

let cart;
let line = prompt();
while (line !== null) {
  const [command, name, price] = line.split(" ");
  if (command === "new") cart = createCart();
  else if (command === "add") cart.add(name, Number(price));
  else if (command === "remove") cart.remove(name);
  else console.log(`${cart.count()} items, total ${cart.total()}`);
  line = prompt();
}
console.log(Object.keys(cart).join(","));

Lesson: Modules: splitting a program into files →