map, filter, reduce

joDMSoluth·2020년 3월 13일
0

함수형프로그래밍

목록 보기
8/17
const products = [
  { name: '반팔티', price: 15000 },
  { name: '긴팔티', price: 20000 },
  { name: '핸드폰케이스', price: 15000 },
  { name: '후드티', price: 30000 },
  { name: '바지', price: 25000 },
]

map

const map = (f, iter) => {
  let res = [];
  for(const p of iter) {
    res.push(f(p));
  }
  return res;
};

let names = [];
for (const p of products) {
  names.push(p.name);
}
console.log(names);

console.log(map(p=>p.name, products));

이터러블 프로토콜을 따른 map의 다형성

console.log(document.querySelectorAll('*').map(el => el.nodeName); // error map 함수 존재x

const it = document.querySelectorAll('*')[Symbol.iterator]();
console.log(it.next());
// 유사배열도 이터러블이므로 이터레이터 사용 가능

function *gen() {
  yield 2;
  if(false) yield 3;
  yield 4;
}

console.log(map(a => a * a, gen());

// ---
// 추가)            
let m = new Map();
m.set('a', 10);
m.set('b', 20);
const it = m[Symbol.iterator]();
console.log(it.next());

console.log(new Map(map(([k, a]) => [k, a * 2], m)));

filter

const filter = (f, iter) => { 
  let res = [];
  for(const a of iter) {
    if(f(a)) res.push(a);
  }
  return res;
}

let under20000 = [];
for(const p of products) {
  if(p.price < 20000) under20000.push(p);
}
console.log(...under20000)

// 위 소스를 대체
console.log(...filter(p=>p.price<20000, products)
    
console.log(filter(n => n % 2, [1, 2, 3, 4]));

console.log(filter(n => n % 2, function *() {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
} ()));

reduce

const nums = [1, 2, 3, 4, 5];

let total = 0;
for(const n of nums) {
  total = total + n;
}
console.log(total);


const reduce = (f, acc, iter) => {
  // 다형성
  if(!iter) {
    iter = acc[Symbol.iterator]();
    acc = iter.next().value;
  }
  // 로직
  for(const a of iter) {
    acc = f(acc, a);
  }
  return acc;
}

const add = (a, b) => a + b;

console.log(reduce(add, 0, [1, 2, 3, 4, 5]));
// 15
console.log(add(add(add(add(0, 1), 2), 3), 4), 5);

// 다형성
console.log(reduce(add, [1, 2, 3, 4, 5]));
// 15

예제)

console.log(reduce((total_price, product) => total_price + product.price, 0, products));

map + filter + reduce

console.log(
  reduce(
    add,
    map(p => p.price,
       filter(p => p.price < 20000, products))));
// filter로 가격이 20000 미만인 거 추출
// map으로 가격만 가져온다.
// reduce로 모든 가격을 더한다.

console.log(
  reduce(
    add,
    filter(n => n >= 20000,
       map(p => p.price, products))));
// map으로 가격 테이블만 가져오기
// filter로 20000 이상의 가격만 가져오기
// reduce로 모든 가격 더하기
profile
풀스택이 되고 싶은 주니어 웹 개발자입니다.

0개의 댓글