Skip to curriculum
Jump to the editor

5.4. A property that cannot go below zero

Easy
Topics
10–20 min

Some numbers must never be negative: items in stock, seats left, a volume level, a counter of unread messages. A bug elsewhere writes stock -= 5 when only 3 are left, and now the shop shows -2 items. Instead of checking at every place that writes, the object itself can guard the value: a property with a getter and a setter decides what is stored.

Write defineNonNegative(object, key, initial) in non-negative.js. It adds a property key to object whose value can never go below zero.

Signature

JAVASCRIPT
function defineNonNegative(object, key, initial) // returns object
  • object: the object to add the property to.
  • key: the property name.
  • initial: the starting value, 0 when missing.
  • Returns object itself.

Requirements

  1. Reading the property gives the current value, starting from initial (0 when missing).
  2. Writing a number from 0 up stores it. Fractions and Infinity are fine.
  3. Writing a negative number stores 0, so object.stock -= 5 stops at 0. Writing -0 stores 0.
  4. Writing anything that is not a number (a string, null, undefined, a boolean, an object, a BigInt) or NaN throws a TypeError, and the value stays what it was.
  5. initial follows the same rules: a negative one becomes 0, and one that is not a number, or NaN, throws a TypeError.
  6. The property is enumerable: it shows up in Object.keys and in JSON.stringify.
  7. No other property is added to the object: the value is not stored in a second, visible property.
  8. Each property has its own value: two keys on one object, or the same key on two objects, never share one. The object's other properties are not changed.

Examples

JAVASCRIPT
const shop = defineNonNegative({ name: "tea" }, "stock", 3);
shop.stock;          // 3
shop.stock -= 5;
shop.stock;          // 0, not -2
shop.stock = 10;
shop.stock;          // 10
JAVASCRIPT
shop.stock = "5";    // TypeError; shop.stock is still 10
shop.stock = NaN;    // TypeError
JAVASCRIPT
JSON.stringify(shop);            // '{"name":"tea","stock":10}'
defineNonNegative({}, "seats").seats;  // 0

Environment

  • Plain JavaScript in a browser page; the tests call the global defineNonNegative from non-negative.js.
  • Every built-in is allowed. Deleting or redefining the property later is out of scope.

Hints

  1. If the value may not live in a property of the object, where can a getter and a setter keep it?
  2. -0 < 0 is false. Which single comparison sends both negatives and -0 to 0?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…