2695. Array Wrapper
Create a class ArrayWrapper that accepts an array of integers. It should support addition and string conversion.
π Problem Statement
- Constructor: Accepts an array of integers.
- Addition ( + operator ): When two
ArrayWrapperinstances are added, the result is the sum of both arraysβ elements. - String Conversion: Using
String(instance)returns a string like"[1,2,3]".
β οΈ 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(",")}]\`;
}
}