Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Chainable Calculator

Object-Oriented Programmingeasy

Course · Section 14: Object-Oriented Programming (OOP) With JavaScript · Lecture 237: Chaining Methods

Build a calculator whose operations chain. Implement `Calculator` (starting value optional, default 0) with `add(n)`, `subtract(n)`, `multiply(n)` returning `this`, and `result()` returning the value.

Examples

Input: new Calculator(10).add(5).subtract(3).multiply(2).result()
Output: 24
(10 + 5 - 3) * 2 = 24.

Sample tests

Input: chain from 10
Output: 24
Input: default start
Output: 7

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • A method that returns nothing breaks the chain.
Approach & explanation (try first)

Returning this from each mutating method enables fluent chaining; result reads the final value.

Loading...
⌘/Ctrl + Enter

Run your code to see results.