list에서 methodName을 정의하면 해당 method를 이용해 return 값을 반환한다.
_.invoke(list, methodName, *arguments)
_.invoke([5, 1, 7], [3, 2, 1], 'sort');
=> [[1, 5, 7], [1, 2, 3]]
_.invoke = function(collection, functionOrKey) {
let result = [];
let args = Array.prototype.slice.call(arguments, 2);
if(typeof arguments[1] === 'string'){
for(let i = 0; i < collection.length; i++){
result.push(collection[i][functionOrKey](args));
}
} else {
for(let i = 0; i < collection.length; i++){
result.push(functionOrKey.apply(collection[i]));
}
}
return result;
};
_.invoke()함수는 두 개 이상의 인수를 전달한다.
첫 번째는 작업할 목록, 두번째는 메서드다. 후속 인수는 목록의 각 요소에 대한 매서드에 전달된다.
.apply()는 목록의 요소를 컨텍스트로 사용해 해당 함수를 호출한다.
let slice = Array.prototype.slice;
args = slice.call(arguments, 2);
// 요약해서 표현하면
let args = Array.prototype.slice.call(arguments, 2);