A checkout form keeps a running amount: add an item, apply a discount, split the bill. Several buttons change the same amount, each wired up with its own handler, and the page shows the steps taken so far. The amount must be shared by every handler, but nothing else should be able to set it, and a bad input must not leave it half-changed.
Write createCalculator(start) in calculator.js. It returns an object whose methods all work on one private running total, and keep a history of the steps.
functioncreateCalculator(start) // returns the calculator object
start: the starting total. A missing start (or undefined) counts as 0.
add(n), subtract(n), multiply(n), divide(n): change the total by n and return the new total.
total(): returns the current total.
history(): returns a new array of the steps taken since the start or the last reset, oldest first, each written as the method name, a space and the number, like "add 5" or "divide -2".
reset(): sets the total back to start, empties the history and returns the total.
The returned object has exactly the seven methods above.
The total starts at start (0 when missing), and every operation works on the total left by the one before.
Each operation returns the new total.
An operation whose n is not a finite number (a string, NaN, Infinity, null, missing) throws a TypeError; divide(0) throws a RangeError. A step that throws changes neither the total nor the history.
history() lists the steps in order, and returns a copy: changing that array does not change the calculator.
reset() goes back to start and clears the history; later steps start from there.
The methods share one total even when taken off the object, and ignore this.
Calculators are independent, and the total cannot be changed by setting properties on the object.