Add kd-tree-javascript (#41653)

This commit is contained in:
Cooper 2020-01-16 09:43:18 -08:00 committed by Eli Barzilay
parent 6170cfa229
commit f40a27d7e3
4 changed files with 86 additions and 0 deletions

30
types/kd-tree-javascript/index.d.ts vendored Normal file
View File

@ -0,0 +1,30 @@
// Type definitions for kd-tree-javascript 1.0
// Project: https://github.com/ubilabs/kd-tree-javascript#readme
// Definitions by: Cooper Bills <https://github.com/coopeyb>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export class kdTree<T> {
// Create a new tree from a list of points, a distance function, and a
// list of dimensions.
constructor(points: T[], distance: (a: T, b: T) => number, dimensions: Array<keyof T>);
// Query the nearest *count* neighbors to a point, with an optional
// maximal search distance.
// Result is an array with *count* elements.
// Each element is an array with two components: the searched point and
// the distance to it.
nearest(point: T, count: number, maxDistance?: number): Array<[T, number]>;
// Insert a new point into the tree. Must be consistent with previous
// contents.
insert(point: T): void;
// Remove a point from the tree by reference.
remove(point: T): void;
// Get an approximation of how unbalanced the tree is.
// The higher this number, the worse query performance will be.
// It indicates how many times worse it is than the optimal tree.
// Minimum is 1. Unreliable for small trees.
balanceFactor(): number;
}

View File

@ -0,0 +1,32 @@
import { kdTree } from 'kd-tree-javascript';
const points = [
{ x: 1, y: 2 },
{ x: 3, y: 4 },
{ x: 5, y: 6 },
{ x: 7, y: 8 },
];
const distance = (a: { x: number; y: number }, b: { x: number; y: number }) => {
return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2);
};
const tree = new kdTree(points, distance, ['x', 'y']); // $ExpectType kdTree<{ x: number; y: number; }>
tree.nearest({ x: 5, y: 5 }, 2); // $ExpectType [{ x: number; y: number; }, number][]
tree.balanceFactor(); // $ExpectType number
tree.insert({ x: 1, y: 2 }); // $ExpectType void
tree.remove({ x: 1, y: 2 }); // $ExpectType void
new kdTree(points, distance, ['x', 'wrongField']); // $ExpectError
tree.nearest({ x: 5, notY: 5 }, 2); // $ExpectError
const wrongDistanceComparison = (a: { notX: number; notY: number }, b: { notX: number; notY: number }) => {
return Math.pow(a.notX - b.notX, 2) + Math.pow(a.notY - b.notY, 2);
};
new kdTree(points, wrongDistanceComparison, ['x', 'y']); // $ExpectError

View File

@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"kd-tree-javascript-tests.ts"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }