Build a Product class that caps live instances at a changing limit and throws UserLimitExceeded

easyAbout 20 minutesUpdated CodingProAsked atChewyclassesstatic-memberscustom-errorsobject-lifetimedependency-injection
Not solved

Share this question

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 that message.
  • It is a real Error subclass: instanceof Error and instanceof UserLimitExceeded are both true, it has a stack, and its name is "UserLimitExceeded".

class Product

  • static limitSource: the object the limit is read from. It starts as Limit. Tests replace it with any object that has a getLimit() method.
  • new Product(name):
    1. name must be a non-empty string, otherwise throw a TypeError.
    2. Call Product.limitSource.getLimit() exactly once. The result must be a non-negative safe integer, otherwise throw a TypeError. If getLimit() itself throws, let that error through.
    3. If the number of live products is below the limit, the product is created: it gets a name property and counts as live.
    4. Otherwise throw a UserLimitExceeded whose message is exactly Product {name} cannot be created. Maximum {limit} products allowed, with the current limit.
    5. 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 returns true. Later calls return false and change nothing.
  • static count (a getter): the number of live products.
  • static reset(): forgets every live product, so count is 0. Calling destroy() on a product created before the reset returns false and 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 creation

Ref. UR-1541 · © UIRound · uiround.com/questions/build-a-product-class-that-caps-live-instances-at-a-changing-limit-and-throws-userlimitexceeded

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment