class Fib implements IterableIterator<number> {
protected fn1 = 0
protected fn2 = 1
constructor(protected maxValue?: number) {}
public next(): IteratorResult<number> {
var current = this.fn1
this.fn1 = this.fn2
this.fn2 = current + this.fn1
if (this.maxValue != null && current >= this.maxValue) {
return {
done: true,
value: null
}
}
return {
done: false,
value: current
}
}
[Symbol.iterator](): IterableIterator<number> {
return this
}
}
let fib = new Fib()
fib.next() //{ done: false, value: 0 }
fib.next() //{ done: false, value: 1 }
fib.next() //{ done: false, value: 1 }
fib.next() //{ done: false, value: 2 }
fib.next() //{ done: false, value: 3 }
fib.next() //{ done: false, value: 5 }
let fibMax50 = new Fib(50)
console.log(Array.from(fibMax50)) // [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
let fibMax21 = new Fib(21)
for (let num of fibMax21) {
console.log(num) //Prints fibonacci sequence 0 to 21
}
Building code with iterators for ES5 target
위의 코드 예제에는 ES6가 필요합니다. 그러나 JS엔진이 Symbol.iterator을 지원한다면 ES5에서도 사용할 수 있습니다. 타겟을 ES5으로 설정하고, ES6 lib를 사용하여 컴파일하면 됩니다 (프로젝트에 es6.d.ts 추가) 컴파일된 코드는 node 4+, Google Chrome 등의 브라우저에서 작동 가능합니다.