实现说明
pulls、counterProtocol、picked 定义在模块顶层,中间不经过函数作用域。
返回值是携带 true 的对象。
使用要点
- 零拉取示例:每个标识符都在语言发行版内部解析。
- 守卫
pulls > 10一旦成立就走提前的return,把后续流程挡掉。 - 跑完文件,输出里会留下标记——
picked:、total next() pulls:。
常见问题
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。 跨调用保留的状态放在这些顶层绑定里:pulls、counterProtocol、picked。
这段代码返回什么?
一个携带 true 的对象。
核心语句
if (pulls > 10) return { done: true, value: undefined };
return { done: false, value: pulls * 10 };
.map((n) => `item-${n}`)
.take(2)
.toArray();
代码示例
let pulls = 0;
// Plain iterator object: implements .next() but does NOT inherit Iterator.prototype
const counterProtocol = {
next() {
pulls++;
if (pulls > 10) return { done: true, value: undefined };
return { done: false, value: pulls * 10 };
},
};
const picked = Iterator.from(counterProtocol)
.filter((n) => n % 20 === 0)
.map((n) => `item-${n}`)
.take(2)
.toArray();
console.log('picked:', JSON.stringify(picked));
// Lazy execution stops pulling from the underlying source as soon as take(2) is satisfied
console.log('total next() pulls:', pulls);