Constellations/js/Geometry/CellSet.js

59 lines
1.3 KiB
JavaScript
Raw Normal View History

import size from Config;
import {isSmaller, plus, zero} from Geometry.Vector;
import * as Vector from Geometry.Vector;
import {at, iter} from Grid.Util;
import * as Matrix from Grid.Util;
import Set;
2022-08-10 21:12:39 +02:00
var CellSet = Set.make(Vector);
2022-08-10 21:12:39 +02:00
return {
CellSet: CellSet,
union: CellSet.union,
rectangle: rectangle,
isochrome: isochrome,
row: row,
column: column
2022-08-10 21:12:39 +02:00
};
function rectangle(origin, delta) {
var cellSet = new CellSet();
iter(Matrix.make(delta), function(_, cell) {cellSet.add(plus(origin, cell));});
return cellSet;
}
function isochrome(coloring, origin) {
var cellSet = new CellSet();
var color = at(coloring, origin);
2022-08-10 21:12:39 +02:00
var queue = [origin];
while(queue.length > 0) {
var cell = queue.shift();
cellSet.add(cell);
2022-08-10 21:12:39 +02:00
for(var d = -1; d < 2; d += 2) {
[plus(cell, Vector.vertical(d)), plus(cell, Vector.horizontal(d))].forEach(
gateKeeper(cellSet, coloring, queue, color)
2022-08-10 21:12:39 +02:00
);
}
}
return cellSet;
2022-08-10 21:12:39 +02:00
}
function gateKeeper(cellSet, coloring, queue, color) {
2022-08-10 21:12:39 +02:00
return function(cell) {
if(isSmaller(zero(), cell)
&& isSmaller(cell, Vector.diagonal(size-1))
2022-08-10 21:12:39 +02:00
&& !cellSet.contains(cell)
&& at(coloring, cell) == color) {
2022-08-10 21:12:39 +02:00
queue.push(cell);
}
}
}
function row(n) {
return rectangle(Vector.vertical(n), Vector.make(1, size));
}
function column(n) {
return rectangle(Vector.horizontal(n), Vector.make(size, 1));
}