feat: QuadTree

This commit is contained in:
cha0s 2019-03-20 18:33:59 -05:00
parent d4951fd641
commit 2da9d73525
3 changed files with 43 additions and 2 deletions

View File

@ -1,5 +1,7 @@
// export * as Matrix from './matrix';
export {QuadTree} from './quadtree';
import * as Rectangle from './rectangle';
export {Rectangle};

View File

@ -1,7 +1,10 @@
{
"name": "@avocado/math",
"version": "1.0.0",
"version": "1.0.1",
"main": "index.js",
"author": "cha0s",
"license": "MIT"
"license": "MIT",
"dependencies": {
"d3-quadtree": "1.0.6"
}
}

36
packages/math/quadtree.js Normal file
View File

@ -0,0 +1,36 @@
import {quadtree} from 'd3-quadtree';
import * as Rectangle from './rectangle';
export class QuadTree {
constructor() {
this.quadTree = quadtree();
}
add(datum) {
this.quadTree.add(datum);
}
remove(datum) {
this.quadTree.remove(datum);
}
search(queryRectangle) {
const nodes = [];
this.quadTree.visit((node, ...nodeRectangle) => {
nodeRectangle[2] -= nodeRectangle[0];
nodeRectangle[3] -= nodeRectangle[1];
if (!Rectangle.intersects(queryRectangle, nodeRectangle)) {
return true;
}
if (4 !== node.length) {
nodes.push(node);
}
});
return nodes.filter((node) => {
return Rectangle.isTouching(queryRectangle, node.data);
});
}
}