javascript / expert
Snippet
Multi-Slot Array Iterator Projection for Next.js Parallel Routes
When managing dynamic parallel route slots in Next.js, custom collection classes implementing Symbol.iterator allow seamless conversion into arrays while flattening nested slot directory segments.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export class RouteSlotCollection implements Iterable<string> {constructor(private slots: Map<string, string[]>) {}*[Symbol.iterator](): Iterator<string> {for (const [slotName, paths] of this.slots.entries()) {for (const path of paths) {yield `@${slotName}/${path}`;}}}toFlattenedArray(): string[] {return Array.from(this);}}
nextjs
Breakdown
1
export class RouteSlotCollection implements Iterable<string> {
Declares an object-oriented collection implementing JavaScript Iterable interface for parallel route segments.
2
constructor(private slots: Map<string, string[]>) {}
Initializes private state mapping slot names to lists of segment path strings.
3
Empty spacing line.
4
*[Symbol.iterator](): Iterator<string> {
Defines custom generator method under Symbol.iterator key allowing native array spread syntax.
5
for (const [slotName, paths] of this.slots.entries()) {
Iterates over entries of the internal slot map structure.
6
for (const path of paths) {
Nested loop traversing every individual segment path stored for a specific parallel route slot.
7
yield `@${slotName}/${path}`;
Emits formatted slot-prefixed path string on demand.
8
}
Closes nested inner path loop.
9
}
Closes outer entry loop.
10
}
Closes Symbol.iterator generator method.
11
Empty spacing line.
12
toFlattenedArray(): string[] {
Provides method to explicitly transform iterator output into standard array.
13
return Array.from(this);
Uses Array.from static utility to collect generator yields into a flattened string array.
14
}
Closes toFlattenedArray method.
15
}
Closes class declaration body.