개발/Javascript

이터레이터와 제너레이터(Iterators and Generators)

DANIEL.OH 2018. 3. 11. 14:02
  • Don't use iterators. Prefer JavaScript's higher-order functions like map() and reduce() instead of loops like for-of.

  • iterators를 이용하지 마십시오. for-of 루프 대신에 map() 과 reduce() 와 같은 JavaScript 고급함수(higher-order functions)를 이용해 주십시오.

    Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side-effects.

    왜? 고급함수는 immutable(불변)룰을 적용합니다. side effect에 대해 추측하는거보다 값을 반환하는 순수 함수를 다루는게 간단하기 때문입니다.

    const numbers = [1, 2, 3, 4, 5];
    
    // bad
    let sum = 0;
    for (let num of numbers) {
      sum += num;
    }
    
    sum === 15;
    
    // good
    let sum = 0;
    numbers.forEach((num) => sum += num);
    sum === 15;
    
    // best (use the functional force)
    const sum = numbers.reduce((total, num) => total + num, 0);
    sum === 15;
  • Don't use generators for now.

  • 현시점에서는 generators는 이용하지 마십시오.

    Why? They don't transpile well to ES5.

    왜? ES5로 잘 transpile 하지 않기 때문입니다.