Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function lineCircleIntersection(l, c) {
const dx = l.p2.x - l.p1.x;
const dy = l.p2.y - l.p1.y;
const dr2 = square(dx) + square(dy);
const cx = c.c.x;
const cy = c.c.y;
const D = (l.p1.x - cx) * (l.p2.y - cy) - (l.p2.x - cx) * (l.p1.y - cy);
const disc = square(c.r) * dr2 - square(D);
if (disc < 0) return []; // No solution
const xa = D * dy / dr2;
const ya = -D * dx / dr2;
if (nearlyEquals(disc, 0)) return [c.c.shift(xa, ya)]; // One solution
const xb = dx * (dy < 0 ? -1 : 1) * Math.sqrt(disc) / dr2;
const yb = Math.abs(dy) * Math.sqrt(disc) / dr2;
return [c.c.shift(xa + xb, ya + yb), c.c.shift(xa - xb, ya - yb)];
}
function circleCircleIntersection(c1, c2) {
const d = Point.distance(c1.c, c2.c);
if (d > c1.r + c2.r) return []; // Circles are separate.
if (d < Math.abs(c1.r - c2.r)) return []; // One circles contains the other.
if (nearlyEquals(d, 0) && nearlyEquals(c1.r,c2.r)) return []; // Circles are the same.
if (nearlyEquals(d, c1.r + c2.r)) return [new Line(c1.c, c2.c).midpoint]; // Circles touch.
const a = (square(c1.r) - square(c2.r) + square(d)) / (2 * d);
const b = Math.sqrt(square(c1.r) - square(a));
const px = (c2.c.x - c1.c.x) * a / d + (c2.c.y - c1.c.y) * b / d + c1.c.x;
const py = (c2.c.y - c1.c.y) * a / d - (c2.c.x - c1.c.x) * b / d + c1.c.y;
const qx = (c2.c.x - c1.c.x) * a / d - (c2.c.y - c1.c.y) * b / d + c1.c.x;
const qy = (c2.c.y - c1.c.y) * a / d + (c2.c.x - c1.c.x) * b / d + c1.c.y;
return [new Point(px, py), new Point(qx, qy)]
}
function circleCircleIntersection(c1, c2) {
const d = Point.distance(c1.c, c2.c);
if (d > c1.r + c2.r) return []; // Circles are separate.
if (d < Math.abs(c1.r - c2.r)) return []; // One circles contains the other.
if (nearlyEquals(d, 0) && nearlyEquals(c1.r,c2.r)) return []; // Circles are the same.
if (nearlyEquals(d, c1.r + c2.r)) return [new Line(c1.c, c2.c).midpoint]; // Circles touch.
const a = (square(c1.r) - square(c2.r) + square(d)) / (2 * d);
const b = Math.sqrt(square(c1.r) - square(a));
const px = (c2.c.x - c1.c.x) * a / d + (c2.c.y - c1.c.y) * b / d + c1.c.x;
const py = (c2.c.y - c1.c.y) * a / d - (c2.c.x - c1.c.x) * b / d + c1.c.y;
const qx = (c2.c.x - c1.c.x) * a / d - (c2.c.y - c1.c.y) * b / d + c1.c.x;
const qy = (c2.c.y - c1.c.y) * a / d + (c2.c.x - c1.c.x) * b / d + c1.c.y;
return [new Point(px, py), new Point(qx, qy)]
}
export function variance(values) {
if (!values.length) return null;
let mean = mean(values);
let sum = 0;
for (let v of values) sum += square(v - mean);
return sum / (values.length - 1);
}
get length() {
return Math.sqrt(square(this.x) + square(this.y));
}
static distance(p1, p2) {
return Math.sqrt(square(p1.x - p2.x) + square(p1.y - p2.y));
}