UNPKG

@thi.ng/grid-iterators

Version:

2D grid and shape iterators w/ multiple orderings

45 lines (44 loc) 1.25 kB
import { __opts } from "./utils.js"; function* hilbert2d(opts) { const { cols, rows, tx } = __opts(opts); let hIndex = 0; let hOrder = 0; while ((1 << hOrder < cols || 1 << hOrder < rows) && hOrder < 15) hOrder++; const numBuckets = 1 << 2 * hOrder; for (let i = 0, n = cols * rows; i < n; i++) { let hx, hy; do { let s, t, comp, swap, cs, sr; s = hIndex | 1431655765 << 2 * hOrder; sr = s >>> 1 & 1431655765; cs = (s & 1431655765) + sr ^ 1431655765; cs = cs ^ cs >>> 2; cs = cs ^ cs >>> 4; cs = cs ^ cs >>> 8; cs = cs ^ cs >>> 16; swap = cs & 1431655765; comp = cs >>> 1 & 1431655765; t = s & swap ^ comp; s = s ^ sr ^ t ^ t << 1; s = s & (1 << 2 * hOrder) - 1; t = (s ^ s >>> 1) & 572662306; s = s ^ t ^ t << 1; t = (s ^ s >>> 2) & 202116108; s = s ^ t ^ t << 2; t = (s ^ s >>> 4) & 15728880; s = s ^ t ^ t << 4; t = (s ^ s >>> 8) & 65280; s = s ^ t ^ t << 8; hx = s >>> 16; hy = s & 65535; hIndex++; } while ( // Dont't emit any outside cells (hx >= cols || hy >= rows || hx < 0 || hy < 0) && hIndex < numBuckets ); yield tx(hx, hy); } } export { hilbert2d };