Last active
June 20, 2017 05:30
-
-
Save marr/4311725d7c7ddc8a44e79447611dcfb1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { pointInPolygon } from './utils'; | |
const Vector = (x, y) => ({ x, y }); | |
it('detects points in polygons', () => { | |
const vertices = [ | |
[1, 1], | |
[1, 4], | |
[4, 4], | |
[4, 1] | |
].map(([x, y]) => Vector(x, y)); | |
const polygon = { vertices }; | |
expect(pointInPolygon(Vector(2, 2), polygon)).toBeTruthy(); | |
//expect(pointInPolygon(Vector(1, 1), polygon)).toBeFalsy(); | |
//expect(pointInPolygon(Vector(1.5333, 2.3434), polygon)).toBeTruthy(); | |
//expect(pointInPolygon(Vector(400, -100), polygon)).toBeFalsy(); | |
//expect(pointInPolygon(Vector(1.01, 1.01), polygon)).toBeTruthy(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { min, max } = Math; | |
export const pointInPolygon = (p, polygon) => { | |
let c = 0; | |
let p1 = polygon.vertices[0]; | |
let p2; | |
let n = polygon.vertices.length; | |
let xinters; | |
for (let i = 1; i <= n; i++) { | |
p2 = polygon.vertices[i % n]; | |
if (p.y > min(p1.y, p2.y) && | |
p.y <= max(p1.y, p2.y) && | |
p.x <= max(p1.x, p2.x) && | |
p1.y !== p2.y) { | |
xinters = (p.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x; | |
if (p1.x === p2.x || p.x <= xinters) { | |
c++; | |
} | |
} | |
p1 = p2; | |
} | |
return c % 2 !== 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment