Build a chainable calculator
A fluent API is just an object whose methods return the object itself, closing over the state they mutate. Getting it right is a good test of whether you understand what return this buys you.
Implement calc(start = 0). It returns an object with add(n), subtract(n), multiply(n) and divide(n), each of which updates the running total and returns the very same object so calls can be chained, plus value(), which returns the current total. divide(0) throws new Error("Cannot divide by zero") and leaves the running total unchanged. Two calculators created separately are independent.
Arguments
startnumber- Starting value for the running total. Defaults to
0.
Returns
{ add(n): this; subtract(n): this; multiply(n): this; divide(n): this; value(): number } — A calculator object whose arithmetic methods return the object itself so calls chain.
Examples
calc(10).add(5).multiply(2).subtract(4).value(); // 26const c = calc(8);
try { c.divide(0); } catch (e) { /* Cannot divide by zero */ }
c.value(); // 8 — rejected operation left the total aloneWhat it has to do
- Each operation returns the same object, so calls chain.
value()returns the running total, andstartdefaults to0.divide(0)throwsError("Cannot divide by zero")without changing the total.- Separate calculators do not share state.
Notes
- Name the returned object (e.g.
const api = { ... }) so each method canreturn api.return thisonly works if the methods are invoked through the object, which chaining does — but naming the object makes the intent obvious. - Check the divisor before mutating the total. A throw halfway through an update leaves state inconsistent.
Stuck? The javascript course covers everything this challenge needs.
- 1.chains operations in order
- 2.starts at zero by default
- 3.divides
- 4.refuses to divide by zero
- 5.returns the same object and keeps instances separate
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.