Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
5.6. Chain method calls (obj.a().b().c())
Easy
Topics
This question is in
5. Objects and property control$("p").addClass("note").show(), query.where("age", 30).orderBy("name").limit(10), expect(x).not.toBe(y): chained calls read like a sentence because every method returns an object the next method can be called on. The simplest kind returns the very same object each time, so every call adds to one shared state.
Write amount(start) in amount.js. It returns an object for building an amount in the Indian number system with chained calls: amount().crore(5).lakh(15).thousand(45).value() is 51545000 (5,15,45,000).
Signature
function amount(start) // returns the chainable objectThe returned object has these methods:
| Method | Adds | Returns |
|---|---|---|
crore(count) | count × 1,00,00,000 | the same object |
lakh(count) | count × 1,00,000 | the same object |
thousand(count) | count × 1,000 | the same object |
hundred(count) | count × 100 | the same object |
ones(count) | count × 1 | the same object |
value() | nothing | the total so far, a number |
start: the starting total, 0 when missing.
Requirements
- The total starts at
start(0 when missing); each unit method addscountof its unit. - Each unit method returns the same object, so calls chain in any order, and a unit can be used more than once.
value()returns the total and changes nothing: it can be called again, and the chain can go on after it.- A chain stored in a variable half-way is the same object and keeps adding to the same total.
- Each call to
amount()has its own total. - A method taken off the object (
const { lakh, value } = amount()) still works and still returns the chain object. - Fractions and negative counts are allowed (
lakh(1.5)adds 1,50,000). - A count or a start that is not a number, or is
NaN, throws aTypeError, and the total does not change.
Examples
amount().crore(5).lakh(15).thousand(45).value(); // 51545000
amount().ones(7).lakh(1).lakh(2).value(); // 300007: any order, repeats add up
amount(500).thousand(2).value(); // 2500const price = amount().lakh(2);
price.thousand(5);
price.value(); // 205000const { lakh, value } = amount();
lakh(3);
value(); // 300000
amount().lakh("5"); // TypeErrorEnvironment
- Plain JavaScript in a browser page; the tests call the global
amountfromamount.js. - Every built-in is allowed. Formatting the total as text ("5,15,45,000") is out of scope.
Hints
- Where can the total live so that every method of one object sees it, but two objects do not share it?
- If a method uses
this, what isthiswhen the method is called on its own, aslakh(3)?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…