Array Wrapper - Problem

Create a class ArrayWrapper that accepts an array of integers in its constructor. This class should have two features:

Addition Operator: When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays.

String Conversion: When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].

Input & Output

Example 1 — Basic Addition and String
$ Input: nums1 = [1,2], nums2 = [3,4]
Output: [10, "[1,2]"]
💡 Note: obj1 + obj2 = (1+2) + (3+4) = 3 + 7 = 10. String(obj1) = "[1,2]"
Example 2 — Empty Array
$ Input: nums1 = [], nums2 = [5]
Output: [5, "[]"]
💡 Note: obj1 + obj2 = 0 + 5 = 5. String(obj1) = "[]" for empty array
Example 3 — Negative Numbers
$ Input: nums1 = [-1,-2], nums2 = [1]
Output: [-2, "[-1,-2]"]
💡 Note: obj1 + obj2 = (-1+-2) + 1 = -3 + 1 = -2. String includes negative numbers

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -1000 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Array Wrapper - Class Implementation INPUT nums1 = [1, 2] 1 2 nums2 = [3, 4] 3 4 ArrayWrapper(nums1) Instance 1: this.nums = [1,2] ArrayWrapper(nums2) Instance 2: this.nums = [3,4] ALGORITHM STEPS 1 Constructor Store nums array in this.nums 2 valueOf() Method Return sum using reduce() this.nums.reduce((a,b)=>a+b,0) 3 toString() Method Return formatted string `[${this.nums.join(",")}]` 4 Using Operators + calls valueOf() String() calls toString() Addition: 1+2 + 3+4 3 + 7 = 10 String(arr1): "[1,2]" FINAL RESULT Output Array: [10, "[1,2]"] arr1 + arr2 = 10 (valueOf sum: 3 + 7) String(arr1) "[1,2]" (toString format) OK Key Insight: JavaScript's valueOf() method is called when an object is used with arithmetic operators like +. The toString() method is called by String() function. Both methods enable custom type coercion behavior. Using reduce() built-in method efficiently sums array elements in a single traversal - O(n) time complexity. TutorialsPoint - Array Wrapper | Built-in Array Methods Approach
Asked in
Google 15 Facebook 12 Microsoft 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen