AniUI Academy

Build a chainable calculator

mediumFunctions & Closures+250 XPPractice

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(); // 26
const c = calc(8);
try { c.divide(0); } catch (e) { /* Cannot divide by zero */ }
c.value(); // 8 — rejected operation left the total alone

What it has to do

  • Each operation returns the same object, so calls chain.
  • value() returns the running total, and start defaults to 0.
  • divide(0) throws Error("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 can return api. return this only 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.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.