Custom Coercion With valueOf and toString
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.
Examples
const a = new NumberList([5, 10]);
const b = new NumberList([20]);
a + b; // 35
String(a);"[5,10]"Constraints
- The array holds numbers and may be empty
Notes
- Define only valueOf and String() prints "[object Object]"; define only toString and + uses it too, so a + b concatenates "[5,10][20]" instead of adding.
Hints
Editorial: Custom Coercion With valueOf and toString
Teaching an object how to convert
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.
Approach
Two methods, two contexts.
Implementation
class NumberList { constructor(nums) { this.nums = nums; } valueOf() { return this.nums.reduce((a, b) => a + b, 0); } toString() { return '[' + this.nums.join(',') + ']'; } }
Worth knowing
+ 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.