개발여행의 블로그

[javaScript] the iteration protocols 예시 본문

개발/javaScript

[javaScript] the iteration protocols 예시

개발 여행 2021. 11. 27. 16:24
728x90

지난 포스팅에서 iterble과 the iterable protocol 그리고 iterator와 the iterator protocol에 대해 알아보았다.

https://developerntraveler.tistory.com/135

 

[JavaScript] 왜 Object(객체)는 Iterable object가 아닌것일까?

콘솔에 이것저것 작성하면서 놀고(?) 있을 때 문득 Object는 왜 iterable 하지 않은지 의문이 생겨서 폭풍 서치를 시작했다. (맞지 않은 내용이 있다면 댓글 부탁드립니다. 미리 감사합니다!) Iterable이

developerntraveler.tistory.com

 

이번 포스팅에서는 the iteration protocols의 예시를 살펴볼 것이다.

 

String은 built-in iterable object 예시 중에 하나이다.

String 의 default iterator 는 string 의 문자를 하나씩 반환한다.

const someString = 'hi';
const iterator = someString[Symbol.iterator]();

iterator + "";                               // "[object String Iterator]"
iterator.next();                             // { value: "h", done: false }
iterator.next();                             // { value: "i", done: false }
iterator.next();                             // { value: undefined, done: true }

 

spread syntax와 같은 built-in construct도 같은 iterable protocol을 준수한다.

따라서 아래의 코드와 같이 spread syntax로 someString을 나타내면 글자 하나 하나를 순회하면서 value값을 리턴한다.

console.log([...someString]); // ["h", "i"]

 

 

[Symbol.iterator] 속성을 지정하여 원하는 iteration을 정의할 수 있다.

// need to construct a String object explicitly to avoid auto-boxing
const someString = new String('hi');

someString[Symbol.iterator] = function () {
  return {
    // this is the iterator object, returning a single element (the string "bye")
    next: function () {
      return this._first ? {
        value: 'bye',
        done: (this._first = false)
      } : {
        done: true
      }
    },
    _first: true
  };
};

console.log([...someString]); 결과를 확인해보면

iterator의 next 메서드를 실행한 결과(['bye'])가 반환된 것을 볼 수 있다.

 

iteration protocol을 준수하는 String은 iterable이면서 iterator이다. someString 문자열을 스프레드 문법으로 나타내면, iterator의 next가 실행되면서 value의 값이 배열 안에 저장되는 것을 알 수 있다.

 

iteration protocol은 인터페이스의 역할을, Array, String, Map, Set, DOM collection과 같은 빌트인 iterable은 데이터 공급자의 역할을, for ... of, Spread syntax, Destructuring assignment, Map, Set의 생성자 등은 데이터 소비자의 역할을 하는 것이다.

 

여기서 가장 중요한 핵심은 iteration potocol데이터 공급자(Array, String, Map, Set, DOM collection과 같은 빌트인 iterable)가 하나의 순회 방식을 사용하도록 규정하여 데이터 소비자(for ... of, Spread syntax, Destructuring assignment, Map, Set의 생성자 등)가 효율적으로 데이터를 사용할 수 있도록 돕는다.

 

이전에 포스팅했던 우리가 사용하는 언어를 예로 들어 설명하면 한국어라는 규칙이 존재하지 않았다면 우리는 적절하게 의사소통하지 못했을 것이다. 결론은 iteration protocol이 존재하기 때문에 효율적으로 데이터를 사용할 수 있다!

 

마지막으로 mdn에 generator를 사용한 예시가 있어서 블로그에 남겨본다

function* makeSimpleGenerator(array) {
  let nextIndex = 0;
  while (nextIndex < array.length) {
    yield array[nextIndex++];
  }
}

const gen = makeSimpleGenerator(['yo', 'ya']);

console.log(gen.next().value); // 'yo'
console.log(gen.next().value); // 'ya'
console.log(gen.next().done);  // true

function* idMaker() {
  let index = 0;
  while (true) {
    yield index++;
  }
}

const it = idMaker()

console.log(it.next().value); // '0'
console.log(it.next().value); // '1'
console.log(it.next().value); // '2'

다음에는 generator에 대해 포스팅 해봐야겠다!

 

출처 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

728x90
Comments