javascript / expert
Snippet
Subclassing Native Array with Custom Symbol.isConcatSpreadable for Next.js Dynamic Route Graph Flattening
This snippet illustrates subclassing the native Array constructor in JavaScript while configuring Symbol.isConcatSpreadable. By overriding this well-known symbol on custom collection objects, Next.js sitemap builders or route graph aggregators can seamlessly flatten custom OOP route collections into plain array concatenations.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export class RouteCollection extends Array {constructor(...routes) {super(...routes);this[Symbol.isConcatSpreadable] = true;}filterActive() {return this.filter(route => !route.disabled);}}export function buildSitemap() {const publicRoutes = new RouteCollection({ path: '/' }, { path: '/about' });const internalRoutes = [{ path: '/dashboard', disabled: true }, { path: '/settings' }];const allRoutes = [].concat(publicRoutes, internalRoutes);return allRoutes;}
nextjs
Breakdown
1
export class RouteCollection extends Array {
Extends native JS Array class to build customized domain collections.
2
this[Symbol.isConcatSpreadable] = true;
Configures well-known Symbol to dictate how Array.prototype.concat flattens the instance.
3
const allRoutes = [].concat(publicRoutes, internalRoutes);
Flattens the custom collection seamlessly alongside raw array elements.