Skip to content

Instantly share code, notes, and snippets.

@woudsma
Last active February 19, 2018 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woudsma/2028bc88089c666c7732c3fc6ebf5992 to your computer and use it in GitHub Desktop.
Save woudsma/2028bc88089c666c7732c3fc6ebf5992 to your computer and use it in GitHub Desktop.
Javascript k-d-tree
npm i k-d-tree
const kd = require('k-d-tree')

const data = new Array(1000)
  .fill()
  .map(() => ({
    type: "Point",
    coordinates: [Math.random(), Math.random()]
  }))

const distFn = (a, b) => Math.pow(a.coordinates[0] - b.coordinates[0], 2) +  Math.pow(a.coordinates[1] - b.coordinates[1], 2)
const tree = new kd(data, distFn)

const point = { type: "Point", coordinates: [0.5, 0.5] }
const maxNeighbors = 10
const maxDist = 0.15
const neighbors = tree.nearest(point, maxNeighbors, maxDist)
// neighbors: [[neighbor, distance], [...]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment