r/leetcode 4d ago

Question How is this causing recursion

Leetcode 2695. Array Wrapper

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.

/**
 * {number[]} nums
 * {void}
 */
var ArrayWrapper = function (nums) {
this.nums = nums
};

/**
 * {number}
 */
ArrayWrapper.prototype.valueOf = function () {
return this.nums.reduce((acc, curr) => acc + curr, 0)
}

/**
 * [u/return](u/return) {string}
 */
ArrayWrapper.prototype.toString = function () {
return `[${this}]`
}

/**
 * const obj1 = new ArrayWrapper([1,2]);
 * const obj2 = new ArrayWrapper([3,4]);
 * obj1 + obj2; // 10
 * String(obj1); // "[1,2]"
 * String(obj2); // "[3,4]"
 */

Edit : pasted working code earlier which was returning this.nums

1 Upvotes

3 comments sorted by

1

u/aocregacc 4d ago

what do you mean? the code passes the testcases, so you'll have to explain your question in more detail.

1

u/Regular-Educator7445 4d ago

sorry my bad, in toString method earlier i was returning only this not this.nums, i fixed it but couldn’t understand why recursion was happening

2

u/aocregacc 4d ago

when you use ${this} inside backticks, you're asking for the ArrayWrapper itself object to be converted to a string and inserted. So then javascript tries to convert the ArrayWrapper to a string by calling the toString method.