@dcl/ecs
Version:
Decentraland ECS
33 lines (32 loc) • 1.09 kB
JavaScript
/**
* Returns true if the given parcels array are connected
*/
export function areConnected(parcels) {
if (parcels.length === 0) {
return false;
}
const visited = visitParcel(parcels[0], parcels);
return visited.length === parcels.length;
}
/**
* Returns true if the given coords are equal
*/
export function isEqual(p1, p2) {
return p1.x === p2.x && p1.y === p2.y;
}
function visitParcel(parcel, allParcels, visited = []) {
const isVisited = visited.some((visitedParcel) => isEqual(visitedParcel, parcel));
if (!isVisited) {
visited.push(parcel);
const neighbours = getNeighbours(parcel.x, parcel.y, allParcels);
neighbours.forEach((neighbours) => visitParcel(neighbours, allParcels, visited));
}
return visited;
}
function getIsNeighbourMatcher(x, y) {
return (coords) => (coords.x === x && (coords.y + 1 === y || coords.y - 1 === y)) ||
(coords.y === y && (coords.x + 1 === x || coords.x - 1 === x));
}
function getNeighbours(x, y, parcels) {
return parcels.filter(getIsNeighbourMatcher(x, y));
}