Array Wrapper
Build an ArrayWrapper 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 ArrayWrapper([1, 2]);
const b = new ArrayWrapper([3, 4]);
a + b; // 10
String(a);"[1,2]"Constraints
- 0 <= nums.length <= 1000
Notes
- Define only one of the two and the other context falls back to "[object Object]".
Hints
Array Wrapper (reference solution)
One way to do it. The Editorial tab walks through why it is written this way.
Solution
1class ArrayWrapper {
2 constructor(nums) { this.nums = nums; }
3 valueOf() { return this.nums.reduce((a, b) => a + b, 0); }
4 toString() { return '[' + this.nums.join(',') + ']'; }
5}Editorial: Array Wrapper
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 ArrayWrapper { 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.
join(",") rather than JSON.stringify gives "[]" for an empty array without a special case. Under the hood both methods are consulted through Symbol.toPrimitive, which you can implement directly if you want full control over the hint.