AniUI Academy
medium+250 XPPractice

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.

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.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.