Skip to content

Commit

Permalink
Allow custom bucket sizes
Browse files Browse the repository at this point in the history
  • Loading branch information
coocos committed Nov 22, 2020
1 parent 09a2591 commit 020e9a1
Showing 1 changed file with 21 additions and 20 deletions.
41 changes: 21 additions & 20 deletions src/quadtree.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const BUCKET_SIZE = 4;

export type Point = {
x: number;
y: number;
Expand Down Expand Up @@ -31,33 +29,23 @@ type Inner = {

export type Node = Leaf | Inner;

export function construct(points: Point[], box: BoundingBox): Node {
export function construct(
points: Point[],
box: BoundingBox,
bucketSize: number = 4
): Node {
let root: Node = {
box,
points: [],
};
for (let point of points) {
root = insert(root, point);
root = insert(root, point, bucketSize);
}
return root;
}

export function pointsWithinArea(node: Node, area: Area) {
if (isLeaf(node)) {
return node.points.filter((point) => pointWithinArea(point, area));
}
let points: Point[] = [];
for (let child of Object.values(node.children)) {
if (boxWithinArea(child.box, area)) {
points = [...points, ...pointsWithinArea(child, area)];
}
}
return points;
}

export function insert(node: Node, point: Point): Node {
export function insert(node: Node, point: Point, bucketSize: number = 4): Node {
if (isLeaf(node)) {
if (node.points.length < BUCKET_SIZE) {
if (node.points.length < bucketSize) {
node.points.push(point);
return node;
}
Expand Down Expand Up @@ -86,6 +74,19 @@ export function insert(node: Node, point: Point): Node {
}
}

export function pointsWithinArea(node: Node, area: Area) {
if (isLeaf(node)) {
return node.points.filter((point) => pointWithinArea(point, area));
}
let points: Point[] = [];
for (let child of Object.values(node.children)) {
if (boxWithinArea(child.box, area)) {
points = [...points, ...pointsWithinArea(child, area)];
}
}
return points;
}

export function nodes(node: Node) {
const queue = [node];
const nodes = [];
Expand Down

0 comments on commit 020e9a1

Please sign in to comment.