Key-Value Cache With Expiry
A key/value cache where every entry expires on its own timer — and setting a key again restarts its clock.
JavaScript · ES6 — Pratik Rai ·
A class that decides what it means to add two of its instances, or print one.
Build a NumberList class taking an array of numbers.
Adding two instances with + gives the sum of every number in both. Passing one to String() gives the numbers comma-separated inside square brackets.
Input:
JSfile.javascript1const a = new NumberList([5, 10]); 2const b = new NumberList([20]); 3a + b; // 35 4String(a);
Output:
"[5,10]"
valueOf answers the numeric context, toString the string one.
When an object appears where a primitive is expected, JavaScript asks it to convert. Which method it asks depends on the context, and that is the whole problem.
Two methods, two contexts.
JSfile.javascript1class NumberList { 2 constructor(nums) { this.nums = nums; } 3 valueOf() { return this.nums.reduce((a, b) => a + b, 0); } 4 toString() { return '[' + this.nums.join(',') + ']'; } 5}
+ asks for a number first, so valueOf answers it. String() and template literals ask for a string, so toString answers those.
Brackets around join(",") give "[]" for an empty array without a special case. When a class defines no Symbol.toPrimitive, the engine calls valueOf and toString itself, in an order set by the hint; defining Symbol.toPrimitive overrides both and receives the hint ("number", "string" or "default") directly.
Goal: Implement valueOf and toString so both coercion contexts behave.
+, or to a string inside a template literal. Objects can control that conversion themselves.valueOf answers numeric contexts and toString answers string ones. Arithmetic and unary + reach for valueOf first; String() and template literals reach for toString.toString, which produces "[object Object]" — the string almost every JavaScript developer has seen in a UI at some point."number", "string" or "default". It gives you one place to handle every context explicitly, which is worth mentioning as the modern answer.Continue learning with these related challenges
A key/value cache where every entry expires on its own timer — and setting a key again restarts its clock.
JavaScript · ES6 — Pratik Rai ·
Fold an array of functions into one, applied right to left.
JavaScript · ES6 — Pratik Rai ·
A once wrapper: the first call runs, every call after it does nothing.
JavaScript · ES6 — Pratik Rai ·
A key/value cache where every entry expires on its own timer — and setting a key again restarts its clock.
JavaScript · ES6
Pratik Rai ·
Fold an array of functions into one, applied right to left.
JavaScript · ES6
Pratik Rai ·
A once wrapper: the first call runs, every call after it does nothing.
JavaScript · ES6
Pratik Rai ·