Published
Edited
Dec 18, 2017
1 fork
9 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
cells = {
// start with one cell that encompasses the full canvas.
let cells = [[1, 1, 10, 10]];
while (true) {
// pick a cell that's at least 2 units long on one axis
let choice = cells
.filter(c => (c[2] - c[0]) + (c[3] - c[1]) > 2)
.sort(() => Math.random() - 0.5)[0];
// if no cells can be split, then we're done.
if (!choice) return cells;
let cellSize = [choice[2] - choice[0], choice[3] - choice[1]];
// splitAxis: 0 for x 1 for y. ensure that we split the cell
// on an axis that's greater than one unit in length.
let splitAxis = cellSize[0] == 1 ? 1 :
cellSize[1] == 1 ? 0 :
Math.round(Math.random());
let replacementCells;
if (splitAxis === 0) {
let splitPoint = Math.floor(Math.random() * (cellSize[0] - 2)) + choice[0] + 1;
replacementCells = [
// left side
[choice[0], choice[1], splitPoint, choice[3]],
// right side
[splitPoint, choice[1], choice[2], choice[3]]
];
} else {
let splitPoint = Math.floor(Math.random() * (cellSize[1] - 2)) + choice[1] + 1;
replacementCells = [
// top side
[choice[0], choice[1], choice[2], splitPoint],
// bottom
[choice[0], splitPoint, choice[2], choice[3]]
];
}
// remove the old unified cell, replace it with two cells
// representing its split.
cells.splice(cells.indexOf(choice), 1, replacementCells[0], replacementCells[1]);
yield Promises.delay(100, cells);
if (cells.length === 20) return;
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more