Build a Product class that caps live instances at a changing limit and throws UserLimitExceeded
Problem
A warehouse can hold only a limited number of products, and the limit is set somewhere else: the platform can raise or lower it at any moment. Write the class that enforces it.
The platform provides a Limit class (it is in the starter code; do not change it). Limit.getLimit() returns the current limit and Limit.setLimit(n) changes it.
class UserLimitExceeded extends Error
new UserLimitExceeded(message)creates an error with thatmessage.- It is a real
Errorsubclass:instanceof Errorandinstanceof UserLimitExceededare bothtrue, it has astack, and itsnameis"UserLimitExceeded".
class Product
static limitSource: the object the limit is read from. It starts asLimit. Tests replace it with any object that has agetLimit()method.new Product(name):namemust be a non-empty string, otherwise throw aTypeError.- Call
Product.limitSource.getLimit()exactly once. The result must be a non-negative safe integer, otherwise throw aTypeError. IfgetLimit()itself throws, let that error through. - If the number of live products is below the limit, the product is created: it gets a
nameproperty and counts as live. - Otherwise throw a
UserLimitExceededwhose message is exactlyProduct {name} cannot be created. Maximum {limit} products allowed, with the current limit. - Whenever the constructor throws, nothing is counted.
destroy(): JavaScript has no destructors, so a product is released by calling this method. The first call frees its slot and returnstrue. Later calls returnfalseand change nothing.static count(a getter): the number of live products.static reset(): forgets every live product, socountis0. Callingdestroy()on a product created before the reset returnsfalseand changes nothing.
If the limit is lowered below the number of live products, the existing products stay. New ones fail until enough are destroyed.
Limit.setLimit(2);
const a = new Product("lamp");
const b = new Product("desk");
Product.count; // 2
new Product("chair"); // throws UserLimitExceeded:
// "Product chair cannot be created. Maximum 2 products allowed"
Product.count; // still 2
a.destroy(); // true
a.destroy(); // false: the slot was already freed
new Product("chair"); // works, count is 2 again
Limit.setLimit(3);
new Product("rug"); // works: the new limit is read on every creationRef. UR-1541 · © UIRound · uiround.com/questions/build-a-product-class-that-caps-live-instances-at-a-changing-limit-and-throws-userlimitexceeded
Unlock this question
Its tests and the tested solution are part of Pro.
- 2
- code listings
- 7
- edge cases
- 4
- follow-up questions
What's inside
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.