← 中文资源

简体中文版本

用 Iterator.from 为普通迭代器接入惰性管道

使用 ES2025 的 Iterator.from 包装只实现了 next() 的普通迭代协议对象,直接串联 filter、map 与 take 等惰性算子,达到上限后立即停止拉取后续元素。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

picked: ["item-20","item-40"]
total next() pulls: 4

实现说明

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);