TobilobaCodes – LeetCode Explorer

2695. Array Wrapper

Create a class ArrayWrapper that accepts an array of integers. It should support addition and string conversion.

πŸ“„ Problem Statement

⚠️ No special methods like toJSON or libraries are allowed. Use built-in JS features.

πŸ’‘ Example


const obj1 = new ArrayWrapper([1, 2]);
const obj2 = new ArrayWrapper([3, 4]);

obj1 + obj2
// ➞ 10

String(obj1)
// ➞ "[1,2]"

🧠 Explanation

JavaScript allows us to override primitive behavior with valueOf() for arithmetic and toString() for string conversion.

We store the array, and define valueOf to return the sum of elements. Then toString returns the formatted string.

βœ… Your Solution


class ArrayWrapper {
  constructor(arr) {
    this.arr = arr;
  }

  valueOf() {
    return this.arr.reduce((sum, num) => sum + num, 0);
  }

  toString() {
    return \`[\${this.arr.join(",")}]\`;
  }
}