Take pure 2D arrays primitives out in a separate module for reuse

This commit is contained in:
Tissevert 2022-08-05 19:40:04 +02:00
parent 3a635cb264
commit 301a1cc895
3 changed files with 29 additions and 17 deletions

View file

@ -1,5 +1,6 @@
import CellSet;
import * as Dom from UnitJS.Dom;
import {iter, square} from Grid.Util;
var grid = {
element: document.getElementById('grid'),
@ -8,14 +9,11 @@ var grid = {
size: null
};
var iter = generate; // alias for more intuitive use (discarding the result)
return {
cell: cell,
clear: clear,
init: init,
get: get,
iter: iter,
};
function init(size, eventHandlers) {
@ -37,26 +35,15 @@ function makeRow(config) {
}
function clear() {
grid.data = generate(function() {return; });
grid.data = square(grid.size);
grid.missing = CellSet.make(
{type: 'rectangle', row: 0, column: 0, width: 8, height: 8}
);
iter(function(row, column) {
iter(grid.data, function(row, column) {
cell(row, column).className = '';
});
}
function generate(f) {
var result = [];
for(var row = 0; row < grid.size; row++) {
result[row] = [];;
for(var column = 0; column < grid.size; column++) {
result[row].push(f(row, column));
}
}
return result;
}
function get() {
return grid;
}

View file

@ -2,6 +2,7 @@ import * as File from WTK.File;
import * as Async from UnitJS.Async;
import Grid;
import Grid.Color;
import iter from Grid.Util;
import Mode;
return {
@ -31,7 +32,7 @@ function load() {
function setGridData(data) {
if(data != undefined) {
Grid.iter(function(row, column) {
iter(data, function(row, column) {
if(data[row][column] != undefined) {
Grid.Color.ize(row, column, data[row][column]);
}

24
js/Grid/Util.js Normal file
View file

@ -0,0 +1,24 @@
return {
generate: generate,
iter: iter,
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++) {
result[row].push(f(row, column));
}
}
return result;
}
function iter(grid, f) {
generate(grid.length > 0 ? grid[0].length : null, grid.length, f);
}
function square(size) {
return generate(size, size, function() {return;});
}