JSFiddle - React, Tailwind, and code Playground
by rgthree
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.min.js"></script>
JavaScript
var Item = function(name, x, y, w, h, mw) {
this.name = name;
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.maxWidth = mw;
};
Item.prototype.isOn = function(x, y) {
return (x >= this.x &&
x <= this.x + this.width - 1 &&
y >= this.x &&
y <= this.x + this.height - 1);
};
var items = [
new Item('a', 0, 0, 1, 1, 2),
new Item('b', 1, 4, 1, 1, 2),
new Item('c', 0, 1, 1, 1, 2),
new Item('d', 0, 2, 1, 1, 2),
];
var COLUNNS = 2;
function findFirstEmptySpace(x, y) {
x = x || 0;
y = y || 0;
console.log('findFirstEmptySpace', x, y);
var isOccupied = false;
for (var i = 0, item; item = items[i]; i++) {
console.log(item.name, item.isOn(x, y));
if (item.isOn(x, y)) {
isOccupied = true;
break;
}
};
if (!isOccupied) {
return {x: x, y: y};
}
x++;
if (x > COLUNNS) {
x = 0;
y++;
}
return findFirstEmptySpace(x, y);
}
var firstEmpty = findFirstEmptySpace();
console.log('First empty spot: ', firstEmpty);