Skip to content

Array-backed

ixfx’s grids are not data structures in the sense of ways of storing & recalling data. But there a few helper functions to have grid semantics on arrays.

A grid can be represented as a one- or two- dimensional array.

// Example: One dimensional representation of a 2x2 grid and data
// 0 1
// 2 3
const arr1 = [ 0, 1, 2, 3 ]
// Example: Two dimensional representation of same grid and data
const arr2 = [
[ 0, 1 ],
[ 2, 3 ]
]

You can see the 2D representation is very grid-like. The 1D representation on the other hand is packed into a series of values. In this form, we need to know the number of columns to ‘decode’ the array and know how to split it up into rows and columns. In the 2D form, we get this from the length of the inner and outer arrays.

Creating

If you already have an array of data, use Array1d.wrap or Array2d.wrap , depending on the representation.

This will return a new object that allows you to read and write with grid semantics, as well as access the underlying array.

Example with the 1D array:

let g = Grids.Array1d.wrap(myArray);
// Get value at cell 10,10, stopping at edge if position passes boundary
g.get({x:10,y:20}, `stop`);
// Set vaue of 2,3 to 'blah'
g = g.set(`blah`, { x: 2, y: 3 });

If you want to go the other way and make an array for a given grid, use Array1d.createArray

// Create an array filled with the value 0 to fit a grid 5x5
const arr = Grids.Array1.createArray(0, { rows: 5, cols: 5 });

Values from coordinates

Grids.values takes a grid and iterator as input and yields cell values

// Iterate over all cells
const cells = Grid.As.cells(grid);
// Get the value
for (const v of Grid.values(grid, cells)) {
// Do something with v...
}

Iterating

By.cellValues iterates over all cell values of a Type Grids.GridReadable . It runs left-to-right, top-to-bottom.

import { Grids } from 'ixfx/geometry.js';
for (const value of Grids.By.cellValues(readableGrid)) {
// use value...
}

By.cellAndValues is similar, but returns the cell position and value, in the form of:

type GridCellAndValue<T> = {
cell: { x: number, y: number }
value: T | undefined
}