LeetCode JavaScript 30 Days Challenge – Day28 – 2695. Array Wrapper

    LeetCode JavaScript 30 Days Challenge

    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].

    建立一個 class 叫做 ArrayWrapper,且接受一個整數陣列們在這個建構函式中。
    這個 class 應該有兩個特點:
    - 當兩個實例被加法運算符號相加時,結果值是兩個陣列中所有元素的總和。
    - 當 String() 函式被呼叫在這個實例時,他將回傳一個逗號分隔的字串符號。
    例如:[1,2,3]。
    

    Example 1:

    Input: nums = [[1,2],[3,4]], operation = "Add"
    Output: 10
    

    Example 2:

    Input: nums = [[23,98,42,70]], operation = "String"
    Output: "[23,98,42,70]"
    

    Example 3:

    Input: nums = [[],[]], operation = "Add"
    Output: 0
    

    solution:
    定義一個 ArrayWrapper 的 constructor function,並接受放入 nums 參數。
    接著建構以下兩個原型:
    valueOf 方法:為計算與回傳 nums 陣列中所有元素的總和,運用陣列的 reduce 搭配箭頭函式來完成。
    toString 方法:為回傳一個包含 nums 陣列的格式化字串,運用 String() 將 nums 陣列轉換成字串,
    並添加”[“, “]”來完成陣列樣式的結果(字串)。

    Code 1: BigO(n)

    var ArrayWrapper = function(nums) {
        this.nums = nums
    };
    
    ArrayWrapper.prototype.valueOf = function() {
        return this.nums.reduce(
            (a, b) => a + b, 0
        )
    };
    
    ArrayWrapper.prototype.toString = function() {
        return `[${String(this.nums)}]`
    };
    

    FlowChart:
    Example 1

    const obj1 = new ArrayWrapper([1,2]);
    const obj2 = new ArrayWrapper([3,4]);
    console.log(obj1 + obj2); // 10
    

    Example 2

    const obj = new ArrayWrapper([23,98,42,70]);
    console.log(String(obj)); // "[23,98,42,70]"
    

    Example 3

    const obj1 = new ArrayWrapper([]);
    const obj2 = new ArrayWrapper([]);
    console.log(obj1 + obj2); // 0