Easy

Method Chaining: Calculator

Prompt

Implement a MathCalculator class that supports method chaining. The calculator should accept an optional initial value in its constructor (default to 0).

  • add(number) — adds the given number to the current total.
  • subtract(number) — subtracts the given number from the current total.
  • multiply(number) — multiplies the current total by the given number.
  • divide(number) — divides the current total by the given number. Should throw an error when dividing by zero.
  • getValue() — returns the current total.
  • All methods except getValue() should return this to enable chaining.
Hint 1

Initialize an instance variable in the constructor to store the calculator's current value. Use a default parameter so it starts at 0 if nothing is passed.

Hint 2

The secret to method chaining is returning this from each method. When add returns this, the caller gets back the calculator instance, so they can immediately call .subtract() on it, and so on.

Solution

Explanation

Method chaining is one of those patterns that you've probably used hundreds of times (think jQuery, D3, or even array methods like .filter().map().reduce()) without necessarily thinking about how it works under the hood. The mechanism is surprisingly simple.

The constructor stores the initial value (or 0 by default) in this.value. Each arithmetic method updates this.value and then returns this, which is the instance itself. That's the entire trick. When you write calc.add(10).multiply(3), the .add(10) call returns the calculator object, and .multiply(3) is called on that returned object. The chain keeps going for as long as each method hands back this.

getValue is the terminator. It returns a number instead of this, which ends the chain. You can think of it like a pipeline: data flows through the chain, getting transformed at each step, and getValue extracts the final result.

The divide method has one extra responsibility: it checks for division by zero and throws an error if you try it. This is important because JavaScript doesn't throw on 10 / 0; it just gives you Infinity. Silently producing Infinity in a calculator would lead to confusing results down the chain, so an explicit error is the right call.

One thing interviewers sometimes look for is whether you handle the constructor's default value cleanly. Using a default parameter (initialValue = 0) is the modern, readable approach. Some candidates use this.value = initialValue || 0, but that has a bug: if someone passes 0 as the initial value, the || would treat it as falsy and override it. Default parameters don't have this problem.

Table of Contents