Skip to content

Commit 4474fed

Browse files
committed
feat[ptr]: 通过 generator API 实现迭代器模式
1 parent aac3331 commit 4474fed

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

  • Design-Pattern/Behavioral/Iterator/generatorEx
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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();

0 commit comments

Comments
 (0)