이터레이터 이해하기

Donghun Seol·2023년 4월 1일
0

이터레이터의 필요성과 활용법

이터레이터를 활용해 전체 배열을 생성하지 않고필요한 원소만 그때그때 꺼내 쓸 수 있다. 이를 통해 효율적인 메모리공간 활용이 가능하다. 일반적으로 배열을 순회하기 위한 방법으로 전통적인 for문 이외에 for..offor..in이 있다.
for...in은 객체의 킷값을 대상으로 순회하므로 범용적으로 사용가능하지만 for...of는 순회대상이 내부적으로 iterator를 지원해야만 사용 가능하다.

단순한 iterator 구현

range의 숫자를 반환하는 일반 이터레이터는 다음과 같이 구현 가능하다.
함수표현식의 반환값이 next()메서드를 포함하는 객체이고, next()함수는 자신의 스코프 밖의 변수인 currentValue를 참조하는 클로저를 형성한다. 클로저 형성을 통해 전역적으로 사용하는 변수를 전역스코프에 담지않고 안전하게 관리하면서 활용가능해졌다. 다만 이러한 형태의 이터레이터에는 for...of문을 사용할 수 없다.

export const rangedIterator = (from: number, to: number) => {
  let currentValue = from
  next() {
    const value = currentValue < to ? currentValue++ : undefined
    const done = value === undefined
    return {value, done}
  }
}

[Symbol.iterator]과 클래스를 활용한 구현

아래와같이 구현하면 for...of를 사용할 수 있다.

export class RagnedIterator {
  constructor(public from:number, public to:number) {}
  [Symbol.iterator]() { // 속성을 정의해준다.
    const that = this
    let currentValue = that.from
    return {
      next() {
        const value = currentValue < that.to ? currentValue++ : undefined
        const done = value == undefined
        return {value, done}
      }
    }
  }
}
profile
I'm going from failure to failure without losing enthusiasm

0개의 댓글