iT邦幫忙

2023 iThome 鐵人賽

DAY 29
0
Software Development

LeetCode-30 Days of JavaScript系列 第 29

LeetCode JS30-Day29 | 2695. Array Wrapper 包裝陣列

  • 分享至 

  • xImage
  •  

LeetCode JS30-Day29 | 2695. Array Wrapper 包裝陣列 Easy

Description❓

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

建立一個類別ArrayWrapper,在其建構函式中接受整數陣列。 這個類別應該有兩個特點:

  • 當使用+運算子將此類別的兩個實例相加時,結果值是兩個陣列中所有元素的總和。
  • 當在實例上呼叫 String() 函數時,將傳回一個用括號括起來的逗號分隔字串。 例如,[1,2,3]

Points

Solution✍️

[ ▶️挑戰這一題 ][ 本日代碼 ]

class ArrayWrapper {
    constructor(nums) {
      this.nums = nums;
    }
    //使用Array.flat(1); 將多維陣列平坦化為一維陣列
    //使用Array.reduce(); 相加所有元素
    valueOf() {
        const flattenArray = this.nums.flat(1);
        return flattenArray.reduce((sum, num) => sum + num, 0);
    }
    //使用Array.join(,) 把所有的元素中間用,隔開並組合成字串 
    toString() {
      return `[${this.nums.join(',')}]`;
    }
}

Testcase

let nums1 = [[1,2],[3,4]]
let ex1 = new ArrayWrapper(nums1);
console.log(ex1.valueOf()); // 10
let nums2 = [[23,98,42,70]]
let ex2 = new ArrayWrapper(nums2);
console.log(ex2.toString()); //[23,98,42,70]
let nums3 = [[],[]]
let ex3 = new ArrayWrapper(nums3);
console.log(ex3.valueOf()); // 0

上一篇
LeetCode JS30-Day28 | 2694. Event Emitter 事件發送器
下一篇
LeetCode JS30-Day30 | 2726. Calculator with Method Chaining 使用方法鍊的計算機
系列文
LeetCode-30 Days of JavaScript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言