silphius/app/util/math.js

74 lines
1001 B
JavaScript
Raw Normal View History

2024-07-04 09:08:47 -05:00
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;
2024-07-03 16:13:14 -05:00
export function clamp(n, min, max) {
return Math.max(min, Math.min(max, n));
}
2024-07-02 16:16:39 -05:00
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);
}
2024-07-02 14:41:54 -05:00
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;
}
2024-07-02 08:05:36 -05:00
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};
}
2024-07-04 09:08:47 -05:00
export function random() {
return Math.random();
}