Recent Posts
Recent Comments
게으른개발너D
[Array] Array Wrapper (method, prototype 만들기) ⭐️ 본문
https://leetcode.com/problems/array-wrapper/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].
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]"
Example 3:
Input: nums = [[],[]], operation = "Add"
Output: 0
Explanation:
const obj1 = new ArrayWrapper([]);
const obj2 = new ArrayWrapper([]);
obj1 + obj2; // 0
Constraints:
- 0 <= nums.length <= 1000
- 0 <= nums[i] <= 1000
- Note: nums is the array passed to the constructor
solution
/**
* @param {number[]} nums
*/
var ArrayWrapper = function(nums) {
this.nums = nums;
};
ArrayWrapper.prototype.valueOf = function() {
return this.nums.reduce((a, b) => a + b, 0);
}
ArrayWrapper.prototype.toString = function() {
return `[${this.nums.join(",")}]`;
}
solution2
class ArrayWrapper {
constructor(nums) {
this.nums = nums;
}
valueOf () {
return this.nums.reduce((a, b) => a + b, 0);
}
toString () {
return `[${this.nums.join(",")}]`;
}
}
'알고리즘 > 과제' 카테고리의 다른 글
[Funtions, Timeout] Execute Cancellable Function With Delay (0) | 2023.07.04 |
---|---|
[Function, Closure] To Be Or Not To Be (0) | 2023.07.04 |
[Function, Closure] Allow One Function Call (함수 한 번만 호출하기) (0) | 2023.07.03 |
[Function, Closure, Class] Counter II (closure 함수 여러개 넣기) ⭐️ (0) | 2023.07.03 |
[Generator] Generate Fibonacci Sequence ⭐️ (0) | 2023.07.03 |
Comments