티스토리 뷰

javascript/알고리즘

2695. Array Wrapper

소영 2024. 7. 2. 21:56

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

 

 

답:

1

var ArrayWrapper = function(nums) {
    this.arrNumsToSum = nums.reduce((acc,cur) => acc + cur,0)
    this.arrToString = `[${this.nums}]`
};

/**
 * @return {number}
 */
ArrayWrapper.prototype.valueOf = function() {
    return this.arrNumsToSum
}

/**
 * @return {string}
 */
ArrayWrapper.prototype.toString = function() {
    return this.arrToString
}

2

/**
 * @param {number[]} nums
 * @return {void}
 */

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

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

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

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

 

this와 prototype

 

javascript에서는 객체를 상속하기 위해 프로토타입이라는 방식을 사용한다. 

 

var ArrayWrapper = function(nums) {
//속성과 메소드 정의
    this.nums = nums
};

var obj1 = new ArrayWrapper();//인스턴스 생성


obj1.valueOf();
//기본 valueOf() 메서드는 this값 자체를 반환하고, 아직 객체가 아닌 경우 객체로 변환한다. 

예시
const obj = {foo:1};
console.log(obj.valueOf === obj) //true

 

object.prototype.valueOf()

- object 인스턴스의 ValueOf() 메서드는 this값을 객체로 변환

- javascript는 객체를 원시값으로 변환하기 위해 valueOf 메서드를 호출

- 원시 값이 예상되는 객체를 만나면 자동으로 호출됨,  그렇기에 직접 메서드를 호출할 필요는 없음.(호출을 해도 되긴 함)

- 숫자 변환 및 기본 변환에 의해 우선적으로 호출됨

 

 

object.prototype.toString()

- object 인스턴스의 toString() 메서드는 객체를 나타내는 문자열을 반환함

- 사용자 지정 유형 강제 로직을 위해 파생 개체로 재정의될 수 있음.

- 객체를 원시값으로 변환하기 위해 toString 메서드를 호출, 원시 값이 예상되는 객체를 만나면 자동으로 호출함

- 문자열 변환에 의해 우선순위로 호출됨.

- "[object Type]"을 반환하며, 이는 객체 유형이다. 

예시

const theDog = new Dog("Gabby", "Lab", "chocolate", "female");

theDog.toString(); // "[object Object]"
`${theDog}`; // "[object Object]"

 

const toString = Object.prototype.toString;


//call 메서드를 사용하면 함수 호출 시 this 값을 명시적으로 설정할 수 있음
//toString 메서드는 this 값에 의존하기 때문에 다른 객체의 문맥에서 호출하면 해당 객체의 타입을 반환할 수 있음
toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]
// Math has its Symbol.toStringTag
toString.call(Math); // [object Math]

toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
댓글