2695. Array Wrapper

Create a class ArrayWrapper that accepts an array of integers in it’s 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:

Example 2:

Example 3:

Constraints:

  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • Note: nums is the array passed to the constructor

From: LeetCode
Link: 2695. Array Wrapper


Solution:

Ideas:
The idea behind this code is to create a class that can wrap an array of numbers and provide two useful methods: valueOf and toString. The valueOf method will add all of the numbers in the array together and return the sum, while the toString method will create a string representation of the array by separating each number with a comma and enclosing the entire list in square brackets.
Code:
/**
 * @param {number[]} nums
 */
var ArrayWrapper = function(nums) {
    this.nums = nums;
};

ArrayWrapper.prototype.valueOf = function() {
    var sum = 0;
    for (var i = 0; i < this.nums.length; i++) {
        sum += this.nums[i];
    }
    return sum;
}

ArrayWrapper.prototype.toString = function() {
    var str = "[";
    for (var i = 0; i < this.nums.length; i++) {
        if (i > 0) {
            str += ",";
        }
        str += this.nums[i];
    }
    str += "]";
    return str;
}

/**
 * const obj1 = new ArrayWrapper([1,2]);
 * const obj2 = new ArrayWrapper([3,4]);
 * obj1 + obj2; // 10
 * String(obj1); // "[1,2]"
 * String(obj2); // "[3,4]"
 */
06-01 21:56