function pointInPoly(p, poly) {
const py = p[1];
const yOrient = (p) => Math.sign(p[1] - py);
const n = poly.length;
let prev = poly[n - 1];
let prevYOr = yOrient(prev);
let count = 0;
for (let i = 0; i < n; i++) {
const q = poly[i];
const yOr = yOrient(q);
if (Math.abs(yOr - prevYOr) >= 1) {
const pOr = orient(prev, q, p);
const far = [Math.max(prev[0], q[0]) * 2, py];
const farOr = orient(prev, q, far);
if (Math.abs(pOr - farOr) == 2) {
if (yOr == 0) {
const next = poly[(i + 1) % n];
const nextYOr = yOrient(next);
if (Math.abs(nextYOr - prevYOr) == 2) count++;
} else {
if (prevYOr != 0) count++;
}
}
}
prevYOr = yOr;
prev = q;
}
return count % 2 == 1;
}