实现说明
重复被限制在 for (let n = 1; n <= 100; n++) 里——其余代码按顺序各跑一遍。
顶层就这几处状态:yielded、firstOver45、ports、hasHighPort。
使用要点
- 严格意义上无依赖——导入清单里没有任何包。
- 每一步打印都带着自己的标签:
firstOver45:、hasHighPort:。
常见问题
这份代码可以原样复制进项目使用吗?
可以。粘进去就能运行,中间没有包管理器的事。 状态都挂在模块顶层:yielded、firstOver45、ports。
核心语句
const totalPorts = Iterator.from(ports).reduce((sum, p) => sum + p, 0);
const hasHighPort = Iterator.from(ports).some((p) => p >= 8000);
const allPositive = Iterator.from(ports).every((p) => p > 0);
代码示例
let yielded = 0;
function* sequence() {
for (let n = 1; n <= 100; n++) {
yielded++;
yield n * 10;
}
}
// drop + find pulls only until the predicate matches once
const firstOver45 = Iterator.from(sequence())
.drop(2)
.find((val) => val > 45);
console.log('firstOver45:', firstOver45, '| yielded:', yielded);
// some short-circuits on a plain Set without building an intermediate array
const ports = new Set([80, 443, 8080, 8443]);
const hasHighPort = Iterator.from(ports).some((p) => p >= 8000);
const allPositive = Iterator.from(ports).every((p) => p > 0);
const totalPorts = Iterator.from(ports).reduce((sum, p) => sum + p, 0);
console.log('hasHighPort:', hasHighPort, '| allPositive:', allPositive, '| sum:', totalPorts);