File tree Expand file tree Collapse file tree
Design-Pattern/Behavioral/Iterator/generatorEx Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ type Book = {
2+ id : number ;
3+ title : string ;
4+ } ;
5+
6+ class BookCollection {
7+ private readonly books : Book [ ] = [ ] ;
8+
9+ add ( book : Book ) : void {
10+ this . books . push ( book ) ;
11+ }
12+
13+ // function*
14+ // Generator 作为具体迭代器:按顺序逐个产出集合元素
15+ * createIterator ( ) : Generator < Book , void , unknown > {
16+ for ( const book of this . books ) {
17+ yield book ;
18+ }
19+ }
20+ }
21+
22+ function runDemo ( ) : void {
23+ const collection = new BookCollection ( ) ;
24+ collection . add ( { id : 1 , title : "Design Patterns" } ) ;
25+ collection . add ( { id : 2 , title : "Refactoring" } ) ;
26+ collection . add ( { id : 3 , title : "Clean Code" } ) ;
27+
28+ console . log ( "--- 手动 next() 遍历 ---" ) ;
29+ const iterator = collection . createIterator ( ) ;
30+ let result = iterator . next ( ) ;
31+ while ( ! result . done ) { // 迭代器对象还没有 done
32+ console . log ( result . value ) ;
33+ result = iterator . next ( ) ;
34+ }
35+
36+ console . log ( "--- for...of 遍历 ---" ) ;
37+ for ( const book of collection . createIterator ( ) ) {
38+ console . log ( `${ book . id } . ${ book . title } ` ) ;
39+ }
40+ }
41+
42+ runDemo ( ) ;
You can’t perform that action at this time.
0 commit comments