Talentd
FleetCode

2695. Array Wrapper

Easy88.6% acceptance

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

  • 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.
  • When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].

Example 1:

Input: nums = [[1,2],[3,4]], operation = "Add"
Output: 10
Explanation:
const obj1 = new ArrayWrapper([1,2]);
const obj2 = new ArrayWrapper([3,4]);
obj1 + obj2; // 10

Example 2:

Input: nums = [[23,98,42,70]], operation = "String"
Output: "[23,98,42,70]"
Explanation:
const obj = new ArrayWrapper([23,98,42,70]);
String(obj); // "[23,98,42,70]"

Example 3:

Input: nums = [[],[]], operation = "Add"
Output: 0
Explanation:
const obj1 = new ArrayWrapper([]);
const obj2 = new ArrayWrapper([]);
obj1 + obj2; // 0

Constraints:

  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • Note: nums is the array passed to the constructor
5:32
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1/**
2 * @param {number[]} nums
3 * @return {void}
4 */
5var ArrayWrapper = function(nums) {
6
7};
8
9/**
10 * @return {number}
11 */
12ArrayWrapper.prototype.valueOf = function() {
13
14}
15
16/**
17 * @return {string}
18 */
19ArrayWrapper.prototype.toString = function() {
20
21}
22
23/**
24 * const obj1 = new ArrayWrapper([1,2]);
25 * const obj2 = new ArrayWrapper([3,4]);
26 * obj1 + obj2; // 10
27 * String(obj1); // "[1,2]"
28 * String(obj2); // "[3,4]"
29 */
Starter codeJavaScriptSpaces: 4
Examples
Input
[[1,2],[3,4]]
"Add"
Input
[[23,98,42,70]]
"String"
Input
[[],[]]
"Add"
Your code is saved on this device.Solution