Skip to content
Exercise · Final project · lesson 7 of 7

Exercise: inventory

Complete the class Inventory, a warehouse that counts the units of each item. Add the field or the constructor that keeps the quantities yourself. The function function createInventory() in the starter code is already finished and must stay: the tests create a warehouse only through it. The methods are these:

  • add(name, qty) puts qty units of the item name into the warehouse;
  • take(name, qty) takes qty units of the item name out of the warehouse, and if there are fewer, it throws a RangeError and leaves the quantity unchanged;
  • count(name) returns how many units of the item the warehouse holds;
  • names() returns an array of the item names in alphabetical order.

Examples:

  • after add("apple", 5) and add("apple", 3): count("apple") → 8
  • after add("pear", 2): take("pear", 3) → throws a RangeError, and count("pear") stays 2
  • after add("pear", 2) and add("apple", 5): names() → ["apple", "pear"]

Constraints: names are non-empty strings of lowercase Latin letters, and qty is an integer greater than 0; for an unknown item count returns 0 and take throws a RangeError; names() returns only the items that are in stock, so an item taken out in full disappears from the list.

Do not add extra imports unless the task says so explicitly.

inventory.js — javascript
javascript · 20 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way