Iterators
Iterators offer a concise and expressive way to traverse a quadrille, especially when combined with filters. Both for...of
and visit
rely on the lazy cells()
generator to yield filtered cells, enabling functional-style iteration without the verbosity and pitfalls of manual indexing.
Filter functions can access the { row, col, value }
cell data, allowing you to express complex cell selections in a single inline predicate.
Manual Iteration Using Nested Loops
The classic approach to traversing a grid—often seen with 2D arrays or matrices—involves nested for
loops:
function callback(row, col) {
/* callback body */
}
for (let row = 0; row < quadrille.height; row++) {
for (let col = 0; col < quadrille.width; col++) {
callback(row, col);
}
}
While straightforward and likely familiar, this pattern is prone to off-by-one and indexing errors, and doesn’t support filtering without additional logic. It’s a good fallback—but modern alternatives are often cleaner and safer.
Method Overview
for...of
: modern, efficient, and expressive. Supports full control flow (break
,continue
, etc.).visit(callback, filter?)
: syntactic sugar forfor...of
, perfect for inline arrow functions. Also supports full cell predicates.cells(filter?)
: generator used by both methods for yielding filtered cells. Use directly when chaining with methods likemap
,reduce
, orArray.from
.