함수형 프로그래밍 map,filter, reduce

Front_H·2022년 7월 18일

javascript

목록 보기
5/5

1. map

const log = console.log;


const products = [
    {name: '반팔티', price: 15000},
    {name: '긴팔티', price: 20000},
    {name: '핸드폰케이스', price: 15000},
    {name: '후드티', price: 30000},
    {name: '바지', price: 25000}
];

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

// 해당 이터레이터의 상품명만 출력 
log(map(p => p.name, products));

// 해당 이터레이터의 기격만 출력 
log(map(p => p.price, products));

// 일반적인 배열이 아니므로  map메서드를 사용할 수 없지만 이터레이터이므로 for-of이 사용가능하다. 
log(map(el => el.nodeName, document.querySelectorAll('*')));

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

// 제네레이터를 통해 생성한 값도 컨트롤 가능
  log(map(a => a * a, gen()));

  let m = new Map();
  m.set('a', 10);
  m.set('b', 20);

 // Map을 통해 생성한 이터레이터도 컨트롤 가능
  log(new Map(map(([k, a]) => [k, a * 2], m)));

2. 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);
  // }
  // log(...under20000);

  log(...filter(p => p.price < 20000, products));

  // let over20000 = [];
  // for (const p of products) {
  //   if (p.price >= 20000) over20000.push(p);
  // }
  // log(...over20000);

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

  log(filter(n => n % 2, [1, 2, 3, 4]));

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

3. reduce

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

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

  const reduce = (f, acc, iter) => {
    // acc가 없는 경우
    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;

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

  log(add(add(add(add(add(0, 1), 2), 3), 4), 5));
  // 15

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


  log(reduce(
      (total_price, product) => total_price + product.price,
      0, products));
profile
drop the bit 0 and 1

0개의 댓글