문제
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].
예제
접근
해당 함수의 인스턴스를 호출할 시 자동으로 nums.prototype.valueOf() 메소드가 실행된다. 따라서 ArrayWrapper 함수 내에서 sumNums 변수에 reduce 메소드를 이용하여 배열 내 원소의 합을 구해주고 valueOf() 메소드 호출 시 해당 값을 반환해준다.
마찬가지로 String(nums) 실행 시에는 nums.prototype.toString() 메소드가 실행된다. 따라서 join 메소드를 활용하여 배열이 String으로 변환된 값을 저장해둔 뒤 toString() 메소드 호출 시 해당 값을 반환해 줄 수 있도록 했다.
코드
/**
* @param {number[]} nums
* @return {void}
*/
var ArrayWrapper = function(nums) {
this.sumNums = nums.reduce((acc, val) => acc + val, 0);
this.arrToStr = "[" + nums.join(",") + "]";
};
/**
* @return {number}
*/
ArrayWrapper.prototype.valueOf = function() {
return this.sumNums;
}
/**
* @return {string}
*/
ArrayWrapper.prototype.toString = function() {
return this.arrToStr;
}
/**
* const obj1 = new ArrayWrapper([1,2]);
* const obj2 = new ArrayWrapper([3,4]);
* obj1 + obj2; // 10
* String(obj1); // "[1,2]"
* String(obj2); // "[3,4]"
*/
'Algorithm' 카테고리의 다른 글
[LeetCode] 2715. Timeout Cancellation (0) | 2024.02.05 |
---|---|
[LeetCode] 2704. To Be Or Not To Be (0) | 2024.02.05 |
[LeetCode] 2677. Chunk Array (0) | 2024.01.31 |
[BOJ] 4779. 칸토어 집합 (1) | 2024.01.30 |
[SWEA] 1230. 암호문3 (1) | 2024.01.29 |