기본 콘텐츠로 건너뛰기

빈 배열로 호출하면 안되요. reduce

 예전에 some, every를 빈배열로 실행하면 어떻게 되는지 확인하였다. 추가적으로 reduce를 빈배열로 호출하면 어떻게 되는지 이야기해보고자 한다.


[1, 2, 3, 4].reduce((a, b) => a + b)

reduce는 위와 같이, 반복적인 작업을 누적 시키고 싶을 때, 사용하곤 한다.


const list = []
list.reduce((a, b) => a + b) // Uncaught TypeError: Reduce of empty array with no initial value

하지만, 빈 배열로 실행을 하게 되면, 위처럼 에러가 발생 하게 된다. 물론 기본값을 설정하게 되면 에러가 발생하지 않는다.


const list = []
list.reduce((a, b) => a + b, 0)


왜 이렇게 구현 되어있을까?

23.1.3.24 Array.prototype.reduce ( callbackfn [ , initialValue ] )





 4번 조건을 보게 되면 알 수 있다.


일단 4번 조건 까지만, 구현 해보자.


Object.defineProperty(Array.prototype, "reduceImpl", {
value: function (callback) {
// 1. Let O be ? ToObject(this value).
const o = Object(this)

// 2. Let len be ? LengthOfArrayLike(O).
const len = o.length || 0

// 3. If IsCallable(callbackfn) is false, throw a TypeError exception.
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function')
}

// 4. If len = 0 and initialValue is not present, throw a TypeError exception.
if(len === 0 && arguments.length < 2) {
throw new TypeError('Reduce of empty array with no initial value')
}

// ...
},
});

위의 코드에서 aruments[1]이 initialValue로 설정을 해야한다. undefined가 초기값이 될 수 있기 때문!





댓글