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)putsqtyunits of the itemnameinto the warehouse;take(name, qty)takesqtyunits of the itemnameout of the warehouse, and if there are fewer, it throws aRangeErrorand 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)andadd("apple", 3):count("apple")→8 - after
add("pear", 2):take("pear", 3)→ throws aRangeError, andcount("pear")stays2 - after
add("pear", 2)andadd("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.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.