Array Wrapper - Problem
Create a powerful ArrayWrapper class that transforms ordinary arrays into smart objects with custom behaviors! ๐
Your mission: Build a JavaScript class that accepts an array of integers in its constructor and implements two magical features:
- Addition Magic: When two
ArrayWrapperinstances are added with the+operator, return the sum of all elements from both arrays - String Transformation: When
String()is called on an instance, return a beautifully formatted comma-separated string surrounded by brackets
Example:
const wrapper1 = new ArrayWrapper([1, 2, 3]); // sum = 6
const wrapper2 = new ArrayWrapper([4, 5]); // sum = 9
console.log(wrapper1 + wrapper2); // Output: 15
console.log(String(wrapper1)); // Output: "[1,2,3]"This problem teaches you about JavaScript operator overloading using valueOf() and toString() methods - essential skills for creating elegant object-oriented solutions!
Input & Output
example_1.js โ Basic Addition
$
Input:
wrapper1 = new ArrayWrapper([1,2,3]); wrapper2 = new ArrayWrapper([4,5]); wrapper1 + wrapper2
โบ
Output:
15
๐ก Note:
The + operator triggers valueOf() on both objects. wrapper1.valueOf() returns 1+2+3=6, wrapper2.valueOf() returns 4+5=9, so the result is 6+9=15.
example_2.js โ String Conversion
$
Input:
wrapper = new ArrayWrapper([1,2,3]); String(wrapper)
โบ
Output:
"[1,2,3]"
๐ก Note:
String() conversion calls the toString() method, which formats the array as a comma-separated string surrounded by brackets.
example_3.js โ Empty Array Edge Case
$
Input:
wrapper1 = new ArrayWrapper([]); wrapper2 = new ArrayWrapper([1,2]); wrapper1 + wrapper2
โบ
Output:
3
๐ก Note:
Empty array has sum 0, so 0 + (1+2) = 3. The toString() of empty array would be "[]".
Constraints
- 1 โค nums.length โค 1000
- -1000 โค nums[i] โค 1000
- Must implement valueOf() and toString() methods
- The solution should work with JavaScript's native + operator and String() function
Visualization
Tap to expand
Understanding the Visualization
1
Object Creation
ArrayWrapper stores the array and defines special methods
2
Addition Operation
+ operator automatically calls valueOf() on both objects
3
String Conversion
String() function automatically calls toString() method
4
Natural Integration
Objects work seamlessly with JavaScript's built-in operators
Key Takeaway
๐ฏ Key Insight: JavaScript's valueOf() and toString() methods enable seamless operator overloading, making custom objects work naturally with built-in operators like + and String().
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code