함수형 프로그래밍에서 map, filter, reduce는 매우 활용이 많이 된다.
아래처럼 만든 함수은 array(프로토타입 기반, 뿌리를 가진 함수) 뿐만 아니라 interable protocal을 따르는 많은 값 또는 gen함수(문장)들을 사용할 수 있다. => 모든 것을 map 할수 있다. => 다형성이 높다
const products = [{name:"티", price: 20000},{name:"반팔티", price: 25000},{name:"니트", price: 30000}]
function map(f,iter){
const res = [];
for(let v of iter){
res.push(f(v));
}
return res;
}
log(map(p=>p.name,products));
const products = [{name:"티", price: 20000},{name:"반팔티", price: 25000},{name:"니트", price: 30000}]
function filter(f,iter){
const res = [];
for(let v of iter){
if(f(v)) res.push(v);
}
return res;
}
log(map(p=>p>20000,products));
const products = [{name:"티", price: 20000},{name:"반팔티", price: 25000},{name:"니트", price: 30000}];
const add = (a,b) => a+b;
function reduce(f,acc,iter){
if(!iter){
iter = acc[Symbol.iterator]();
acc = iter.next().value;
}
for(let v of iter){
acc=f(acc,v)
}
return acc;
}
console.log(reduce(add,[1,2,3,4,5]));
console.log(reduce(add,p=>p.price, filter(p=>p>20000,products)));