ES6 Iterator & Generator 본문

2021 프론트 엔드 로드맵 따라가기/JS

ES6 Iterator & Generator

알 수 없는 사용자 2021. 6. 15. 04:34

1. Iterator

next라는 함수를 가진 객체를 리턴하여 인자로 전달받은 것을 반복할 수 있도록 한다. 사실 이 개념은 원래부터 존재하는 것이지만 ES6에서 이러한 형태를 하나의 프로토콜(규약)로 제공함에 의미가 있는 것 같다. 이러한 표현방법은 Generator에서도 사용된다.

// Iterator Example
function nameIterator(names) {
  let nextIndex = 0;

  return {
    next: function () {
      return nextIndex < names.length ?
      {value: names[nextIndex++], done: false} :
      {done: true}
    }
  }
}

// Create an array of names
const namesArr = ["Jack", "Jill", "John"];

// init iterator and pass in names array
const names = nameIterator(namesArr);
console.log(names.next());
console.log(names.next());
console.log(names.next());
console.log(names.next());

 

2. Generator

 

뭔가를 생성하기 위해 만들어진 객체인 것 같다. 내부가 정확히 어떻게 구현되어 있는 것인지 파악하지 못해 정말 혼란스럽지만 받아들이기 위해 노력중이다.

 

Generator 임을 표기하기 위해 function 키워드 오른쪽에 *를 붙이며, yield를 이용해 해당 값을 value로 리턴한다.

리턴 양식은 Iterator와 같다.

 

Generator 내부의 while 문을 무한루프로 만들어도 실제 함수호출 시 무한루프가 되지 않는다. 무한으로 증가할 수 있다는 표현을 뜻하는 것 같다. 이 또한 정확한 내부구조를 모르기 때문에 알아나가야 하는 부분이다.

 

// Generator example
function* sayNames() {
  yield "Jack";
  yield "Jill";
  yield "John";
}

const name = sayNames();

console.log(name.next());
console.log(name.next());
console.log(name.next());

// ID Creator
function* createIds() {
  let index = 0;

  while(true) {
    yield index++;
  }
}

const gen = createIds();

console.log(gen.next());
console.log(gen.next());
console.log(gen.next());

 

Comments