Last active
August 31, 2019 08:05
-
-
Save behnood-eghbali/16f59f8dbb99297b6379b0b8f2ba0558 to your computer and use it in GitHub Desktop.
Iterators (TypeScript) forked from https://basarat.gitbooks.io/typescript/docs/iterators.html#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Iterator<T> { | |
next(value?: any): IteratorResult<T>; | |
return?(value?: any): IteratorResult<T>; | |
throw?(e?: any): IteratorResult<T>; | |
} | |
interface IteratorResult<T> { | |
done: boolean; | |
value?: T; | |
} | |
class Component { | |
constructor (public name: string) {} | |
} | |
class Data implements Iterator<Component> { | |
private pointer = 0; | |
constructor(public name: string, public components: Component[]) {} | |
public next(): IteratorResult<Component> { | |
if (this.pointer < this.components.length) { | |
return { | |
done: false, | |
value: this.components[this.pointer++] | |
} | |
} else { | |
return { | |
done: true | |
} | |
} | |
} | |
} | |
let data = new Data("ABCD", [new Component("first"), new Component("second"), new Component("third"), new Component("fourth")]); | |
let iteratorResult1 = data.next(); //{ done: false, value: Component { name: 'first' } } | |
let iteratorResult2 = data.next(); //{ done: false, value: Component { name: 'second' } } | |
let iteratorResult3 = data.next(); //{ done: false, value: Component { name: 'third' } } | |
let iteratorResult4 = data.next(); //{ done: false, value: Component { name: 'fourth' } } | |
let iteratorResult5 = data.next(); //{ done: true } | |
let component = iteratorResult1.value; //Component { name: 'first' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment