[Medium] LeetCode JS 30 - 2695. Array Wrapper

March 6, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2695. Array Wrapper

Question Prompt

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].
// Example 1:
Input: nums = [[1,2],[3,4]], operation = "Add"
Output: 10
Explanation:
const obj1 = new ArrayWrapper([1,2]);
const obj2 = new ArrayWrapper([3,4]);
obj1 + obj2; // 10

// Example 2:
Input: nums = [[23,98,42,70]], operation = "String"
Output: "[23,98,42,70]"
Explanation:
const obj = new ArrayWrapper([23,98,42,70]);
String(obj); // "[23,98,42,70]"

Solutions

Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!

This is a straightforward. We first have a function constructor ArrayWrapper. Inside the constructor function: this refers to the newly created object.  this.nums = nums assigns the input array (nums) to a property called nums within the new object.

var ArrayWrapper = function (nums) {
  this.nums = nums;
};

For valueOf , we want the + operator to sum up the elements of multiple ArrayWrapper instances. The reduce method is a good fit for this because it's designed to take an array and iteratively "reduce" it down to a single value. The reduce essentially adds the value to the accumulator and returns the new summed value.

// Simulating addition behavior
ArrayWrapper.prototype.valueOf = function () {
  return this.nums.reduce((sum, value) => sum + value, 0);
};

Then, for toString , we simply join every nums by comma, and then add [ and ]

// Controlling string representation
ArrayWrapper.prototype.toString = function () {
  return `[${this.nums.join(",")}]`;
};

Or we can rewrite it using the class syntax

class ArrayWrapper {
	constructor(nums) {
	  this.nums = nums
	}

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

	toString() {
		return `[${this.nums.join(',')}]`;
	}
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee