map
- 이터러블 프로토콜을 따르는 함수
- Iterable 을 순회하며 각각의 값을 function 'f'를 이용해 수행후 반환한다.
/**
* @param {function=} f
* @param {iterable=} iter
*/
const map = (f, iter) =>{
let res = [];
for (const i of iter){
res.push(f(i));
}
return res;
}
이터러블 프로토콜을 따른 map의 다형성
- iterable protocol을 따르는 객체들은 모두 map을 사용가능하다.
- map함수는 iterable protocol을 따르는 for문을 사용하여 순회를 할 수 있다.
❓querySelectorAll은 map이 동작할까?
- NodeList에는 map이 따로 정의되어있지 않기 때문에 동작하지 않는다.
document.querySlectorAll("*").map(...); //error function is not defined (map)
❗하지만, iterable protocol을 따르기 때문에 순회로직 사용가능.
const map = (f, iter) =>{
let res = [];
for (const i of iter){
res.push(f(i));
}
return res;
}
console.log(map(el=>el.nodeName, document.querySelectorAll('*')));
//["HTML", "HEAD", "SCRIPT", "SCRIPT", "BODY"...]
function *gen(){
yield 2;
yield 3;
yield 4;
}
console.loglog(map(a=>a*a, gen()); // 4, 9, 16