javascript / expert
Snippet
Custom Iterators with Symbol.iterator
The iteration protocol allows objects to define their own iteration behavior. Using generator functions within Symbol.iterator enables lazy evaluation, which is essential for processing potentially infinite or large datasets in Next.js without consuming excessive memory upfront.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class DataRange {constructor(private start: number, private end: number) {}*[Symbol.iterator]() {for (let i = this.start; i <= this.end; i++) {yield i;}}}const range = new DataRange(1, 1000);for (const num of range) {if (num > 5) break;console.log(num);}
nextjs
Breakdown
1
*[Symbol.iterator]() { ... }
Defines a generator function as the default iterator for the class.
2
yield i;
Produces the next value in the sequence on demand, pausing execution until requested again.
3
for (const num of range) { ... }
Consumes the custom iterator using the standard loop syntax.