interable용 map, filter, reduce 만들기

boyeonJ·2023년 6월 19일
0
post-thumbnail

함수형 프로그래밍에서 map, filter, reduce는 매우 활용이 많이 된다.

아래처럼 만든 함수은 array(프로토타입 기반, 뿌리를 가진 함수) 뿐만 아니라 interable protocal을 따르는 많은 값 또는 gen함수(문장)들을 사용할 수 있다. => 모든 것을 map 할수 있다. => 다형성이 높다

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));

filter

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));

reduce

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]));

한꺼번에 사용하기

  1. 20000원 이상 상품의
  2. price를 모아서
  3. 다 합치기


console.log(reduce(add,p=>p.price, filter(p=>p>20000,products)));

0개의 댓글