silphius/app/util/math.js
2024-07-04 09:08:47 -05:00

74 lines
1001 B
JavaScript

export const {
abs,
acos,
acosh,
asin,
asinh,
atan,
atanh,
atan2,
ceil,
cbrt,
expm1,
clz32,
cos,
cosh,
exp,
floor,
fround,
hypot,
imul,
log,
log1p,
log2,
log10,
max,
min,
round,
sign,
sin,
sinh,
sqrt,
tan,
tanh,
trunc,
E,
LN10,
LN2,
LOG10E,
LOG2E,
PI,
SQRT1_2,
SQRT2,
} = Math;
export function clamp(n, min, max) {
return Math.max(min, Math.min(max, n));
}
export function distance({x: lx, y: ly}, {x: rx, y: ry}) {
const xd = lx - rx;
const yd = ly - ry;
return Math.sqrt(xd * xd + yd * yd);
}
export function intersects(l, r) {
if (l.x0 > r.x1) return false;
if (l.y0 > r.y1) return false;
if (l.x1 < r.x0) return false;
if (l.y1 < r.y0) return false;
return true;
}
export function normalizeVector({x, y}) {
if (0 === y && 0 === x) {
return {x: 0, y: 0};
}
const k = 1 / Math.sqrt(x * x + y * y);
return {x: x * k, y: y * k};
}
export function random() {
return Math.random();
}