visit(callback, filter?)

visit(callback, filter?)

A syntactic sugar for the for...of loop. Internally defined as:

visit(callback, filter) {
  for (const cell of this.cells(filter)) {
    callback(cell);
  }
}

It simplifies iteration over cells by calling callback on each { row, col, value } cell object. Ideal for concise arrow functions and inline operations.

⚠️
Use for...of instead if you need to break early from the loop.

Example

(move mouse to highlight 🐸 filled cells in the hovered col, and click to randomize q)

code
Quadrille.cellLength = 50;
let q, hint;

function setup() {
  createCanvas(8 * Quadrille.cellLength, 8 * Quadrille.cellLength);
  // Create q with random 🐸, 🐯 and 🐮 emojis, 15 each
  q = createQuadrille(8, 8).rand(15, '🐸').rand(15, '🐯').rand(15, '🐮');
  highlight();
}

function draw() {
  background('#D7BDE2');
  drawQuadrille(q);
  drawQuadrille(hint);
}

function mousePressed() {
  q.randomize();
  highlight();
}

function mouseMoved() {
  highlight();
}

function highlight() {
  hint = createQuadrille(8, 8);
  // Visit all 🐸 cells in the current mouse column,
  // filling the hint cell with translucent black for visual feedback
  q.visit(({ row, col }) => hint.fill(row, col, color(0, 140)), {
    value: v => v === '🐸',    // Only 🐸 values
    col: c => c === q.mouseCol // Only current column
  });
}
ℹ️
This example is a direct adaptation of the corresponding for…of example.
Additional examples from the for...of section can be rewritten using visit following the same pattern.

Syntax

visit(callback, filter?)

Parameters

ParamDescription
callbackFunction to execute on each matching cell. Receives a { row, col, value } object as argument
filterRestricts which cells are visited. All cells are included if this parameter is omitted or undefined. It can be:
  • a value collection (Array or Set)
  • a predicate function (value => boolean)
  • an object with optional value, row, and/or col predicates