Array Wrapper
ClassesCoercion
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
Example 1
Input
const a = new ArrayWrapper([1, 2]);
const b = new ArrayWrapper([3, 4]);
a + b; // 10
String(a);Output
"[1,2]"Explanation
valueOf answers the numeric context, toString the string one.
Constraints
- 0 <= nums.length <= 1000
Notes
- Define only one of the two and the other context falls back to "[object Object]".
Hints
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.
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it