import Function from "./Function"; export default class InfiniteIterator implements IterableIterator { private current: E; private nextElement: E; constructor(private initial: E, private func: Function) { this.current = null; this.nextElement = initial; } public static of(initial: E, func: Function): InfiniteIterator { return new InfiniteIterator(initial, func); } public [Symbol.iterator](): IterableIterator { return this; } public reset(): void { this.current = null; this.nextElement = this.initial; } public hasNext(): boolean { try{ if(this.nextElement == null){ this.nextElement = this.func(this.current); } return this.nextElement != null; } catch(e){ return false; } } public next(): IteratorResult { if(this.nextElement == null){ throw new Error("No more elements"); } this.current = this.nextElement; this.nextElement = null; return { value: this.current, done: this.hasNext() }; } }