[Javascript] Generator & Iterators exercise
Generator can run with for .. of
and ...
, which will only emit yield
values
For example:
function* count() {
yield 1;
yield 2;
return 3;
}
for (const value of count()) {
console.log(value) // 1, 2
}
console.log([...count()]) // [1, 2]
Iterator
Using [Symbol.iterator]()
which should return next()
function:
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return {done: false, value: this.current++}
} else {
return {done: true}
}
}
}
}
}
console.log([...range]) // [1,2,3,4,5]
Or we can also just do geneator appraoch:
const range = {
from: 1,
to: 5,
*[Symbol.iterator]() {
for (let i = this.from; i <= this.to; i++) {
yield i
}
}
}
console.log([...range]) // [1,2,3,4,5]
One usecase for geneator and iterator is that not overload the data, everytime can just load a small tunck of data to process with next()
call instead of loading the whole data into memory
Delegating a yield
function* gen1() {
yield 2;
yield 3;
}
function* gen2() {
yield 1;
yield* gen1() // delegating a yiled*, yield* must used with iterable yiled* [2,3]
yield 4;
}
console.log([...gen2()]) // [1,2,3,4]
分类:
Javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-03-13 [HTML5] Correctly Define Heading Levels of a Web Page
2020-03-13 [Functional Programming] Function modelling -- 3. Reader Monad
2020-03-13 [Functional Programming] 1. Function modelling -- Combine functions
2019-03-13 [Algorithm] Universal Value Tree Problem
2019-03-13 [HTML5] Using the focus event to improve navigation accessibility (nextElementSibling)
2019-03-13 [Javascript] Coding interview problem: Scheduler functional way
2018-03-13 [HTML 5] Atomic Relevant Busy