Iterator cung cấp cách access tuần tự các elements của collection mà không expose underlying representation.
- JavaScript triển khai Iterator Protocol tự nhiên: object là iterator nếu có
next()method trả về{ value, done }.
Ví dụ custom iterator:
typescript
class Range {
constructor(private start: number, private end: number) {}
[Symbol.iterator]() {
let current = this.start
const end = this.end
return {
next() {
return current <= end
? { value: current++, done: false as const }
: { value: undefined, done: true as const }
}
}
}
}
// Dùng trong for...of, spread, destructuring:
const range = new Range(1, 5)
for (const n of range) console.log(n) // 1 2 3 4 5
console.log([...new Range(1, 3)]) // [1, 2, 3]Generator functions (function*) là sugar syntax tạo iterator/iterable.
- Dùng khi: cần traverse collection mà không expose structure; khi muốn lazy evaluation (generate values on demand — tiết kiệm memory cho large datasets).
- Trong React, Suspense và streaming server rendering dùng iterator concept.
Iterator provides a way to sequentially access elements of a collection without exposing its underlying representation.
- JavaScript implements the Iterator Protocol natively: an object is an iterator if it has a
next()method that returns{ value, done }. - Custom iterator example:
typescript
class Range {
constructor(private start: number, private end: number) {}
[Symbol.iterator]() {
let current = this.start
const end = this.end
return {
next() {
return current <= end
? { value: current++, done: false as const }
: { value: undefined, done: true as const }
}
}
}
}
// Works with for...of, spread, and destructuring:
const range = new Range(1, 5)
for (const n of range) console.log(n) // 1 2 3 4 5
console.log([...new Range(1, 3)]) // [1, 2, 3]Generator functions (function*) are syntactic sugar for creating iterators/iterables.
- Use it when you need to traverse a collection without exposing its structure, or when you want lazy evaluation (generating values on demand to save memory with large datasets).
- In React, Suspense and streaming server rendering use iterator concepts.