ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JS] 제너레이터
    기초/자바스크립트 2022. 12. 17. 00:40

    인프런 강의 정리

    함수형 프로그래밍과 Javascript ES6+

     

    일반함수 이름에 *을 붙여 제너레이터 함수를 만든다

    제너레이터 함수 : 이터레이터를 만들어준다.

     

    마지막 return 값은 done을 할 때 반환되는 값이다.

    function *func() {
        yield 1;
        if ( false ) yield 2;
        yield 3;
    }

     

    제너레이터는 문장을 순회할 수 있는 값으로 만들 수 있다.

    제너레이터를 통해 순회할 수 있는 이터러블을 쉽게 만들 수 있다.

     

    //제너레이터 코드를 이용한 홀 수 이터러블 만들기

    //1씩 무한하게 증가시키는 함수
    function* infinity(i = 0) {
      while (true) yield i++;
    }
    
    //1씩 무한하게 감소시키는 함수
    function* infinity2(i = 0) {
      while (true) yield i--;
    }
    
    // 입력된 l까지 입력된 iter를 통해 생성하는 함수
    function* limit(l, iter) {
      for (const a of iter) {
        yield a;
        if (a == l) return;
      }
    }
    
    // odds paramter : value > 0
    // 1부터 입력된 양수 l까지 홀수만 생성하는 함수
    function* odds(l) {
      for (const a of limit(l, infinity(1))) {
        if (a % 2) yield a;
      }
    }
    
    // odds2 paramter : value < 0
    // -1부터 입력된 음수 l까지 홀수만 생성하는 함수
    function* odds2(l) {
      for (const a of limit(l, infinity2(-1))) {
        if (a % 2) yield a;
      }
    }
    
    for (const a of odds(40)) console.log(a); // 1 3 5 ... 39
    for (const a of odds2(-40)) console.log(a); // 1 3 5 ... 39

     

    # for of, 전개 연산자, 구조 분해, 나머지 연산자

    console.log(...odds(10)); // 1 3 5 7 9
    console.log([...odds(10), ...odds(20)]); // [1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
    
    const [head, ...tail] = odds(5);
    console.log(head); // 1
    console.log(tail); // 3 5
    
    const [a, b, ...rest] = odds(10);
    console.log(a); // 1
    console.log(b); // 3
    console.log(rest); // 5 7 9

     

    '기초 > 자바스크립트' 카테고리의 다른 글

    [JS] Map, Filter, Reduce  (0) 2022.12.17
    [JS] 일급 함수와 고차함수  (0) 2022.12.14
    GridSatck (Test.html)  (0) 2022.03.16
    [JS] 모자이크 처리  (2) 2022.03.04
    [Javascript] OpenLayers + GeoServer + PostGIS + VWORLD + WFS,WMS  (6) 2020.11.11

    댓글

Designed by Tistory.