Constellations/js/Grid/Util.js

70 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2022-08-10 21:12:39 +02:00
import * as Vector from Geometry.Vector;
return {
make: make,
2022-08-10 21:12:39 +02:00
at: at,
asAFunction: asAFunction,
2022-08-10 21:12:39 +02:00
column: column,
generate: generate,
iter: iter,
2022-08-10 21:12:39 +02:00
row: row,
set: set,
square: square
};
function generate(width, height, f) {
var result = [];
for(var row = 0; row < height; row++) {
result[row] = [];;
for(var column = 0; column < width; column++) {
2022-08-10 21:12:39 +02:00
result[row].push(f(Vector.make(row, column)));
}
}
return result;
}
function make(width, height) {
if(width instanceof Object && width.row != undefined) {
height = width.row;
width = width.column;
}
return Array.from({length: height}).map(
function() {return Array.from({length: width});}
);
}
function iter(grid, f) {
map(grid, f);
}
function map(grid, f) {
return grid.map(function(rowArray, row) {return rowArray.map(
function(value, column) {return f(value, Vector.make(row, column), grid);}
)});
}
2022-08-10 21:12:39 +02:00
function square(size, value) {
var generator = value instanceof Function ? value : function() {return value;};
return map(make(size, size), function(_, cell) {return generator(cell);});
2022-08-10 21:12:39 +02:00
}
function at(grid, vector) {
return grid[vector.row][vector.column];
}
function asAFunction(grid) {
return function (vector) {return at(grid, vector);};
}
2022-08-10 21:12:39 +02:00
function set(grid, vector, value) {
return grid[vector.row][vector.column] = value;
}
function row(grid, n) {
return grid[n];
}
function column(grid, n) {
return grid.map(function(row) {return row[n];});
}