Implement createCounter with step, min/max bounds, and listeners
A product page has a quantity stepper: − and + buttons around a number. Quantity can never drop below 1 or exceed the stock on hand, some products are sold in packs of 6, and the cart badge in the header must update whenever the quantity changes. The UI should not have to repeat that logic, so you are building the counter behind it.
Implement createCounter(options). It returns a new counter object.
const counter = createCounter({ initial, step, min, max });
counter.get() // => current value
counter.increment(times?) // => new value
counter.decrement(times?) // => new value
counter.set(value) // => new value
counter.reset() // => new value
counter.subscribe(listener) // => unsubscribe function
options is optional, and so is each field in it.
initial (default 0): the starting value.step (default 1): how much one increment or decrement moves the value.min (default -Infinity) and max (default Infinity): the allowed range. You can assume min <= max.increment(times = 1) adds step × times; decrement(times = 1) subtracts it.set(value) sets the value directly.reset() goes back to the starting value.[min, max]: anything above max becomes max, anything below min becomes min. This includes the initial value, so createCounter({ initial: 50, max: 20 }) starts at 20, and reset() returns to 20.subscribe returns the value after the change.const { increment } = counter; increment();subscribe(listener) registers listener(next, previous) and returns a function that unregisters it. Calling that function more than once is harmless.increment() while already at max), no listener runs.const quantity = createCounter({ initial: 1, min: 1, max: 10, step: 2 });
quantity.subscribe((next, previous) => console.log(`${previous} → ${next}`));
quantity.increment(); // => 3 logs "1 → 3"
quantity.increment(3); // => 9 logs "3 → 9"
quantity.increment(); // => 10 logs "9 → 10" (clamped to max)
quantity.increment(); // => 10 no log, nothing changed
quantity.set(99); // => 10 no log
quantity.decrement(20); // => 1 logs "10 → 1"
quantity.set(6); // => 6 logs "1 → 6"
quantity.reset(); // => 1 logs "6 → 1"
quantity.get(); // => 1