diginext-utils
Version:
README.md
78 lines (77 loc) • 2.39 kB
JavaScript
const DEG2RAD = Math.PI / 180;
const RAD2DEG = 180 / Math.PI;
export const randRound = (number) => {
return Math.round(Math.random() * number);
};
export const rand = (number) => {
return (Math.random() - Math.random()) * number;
};
export const randHalt = (number) => {
var rand = Math.random() - Math.random();
var res;
if (rand > 0) {
res = rand * (number / 2) + number / 2;
}
else {
res = rand * (number / 2) - number / 2;
}
return Math.abs(res);
};
export const randInt = (low, high) => {
return low + Math.floor(Math.random() * (high - low + 1));
};
export const randFloat = (low, high) => {
return low + Math.random() * (high - low);
};
export const degToRad = (degrees) => {
return degrees * DEG2RAD;
};
export const radToDeg = (radians) => {
return radians * RAD2DEG;
};
export const clamp = (value, min, max) => {
const result = Math.max(min, Math.min(max, value));
return Number.isFinite(result) ? result : 0;
};
export const degBetweenPoints360 = (cx, cy, ex, ey) => {
let theta = degBetweenPoints(cx, cy, ex, ey); // range (-180, 180]
if (theta < 0)
theta = 360 + theta; // range [0, 360)
return Number.isFinite(theta) ? theta : 0;
};
export const degBetweenPoints = (cx, cy, ex, ey) => {
const dy = ey - cy;
const dx = ex - cx;
let theta = Math.atan2(dy, dx); // range (-PI, PI]
theta *= 180 / Math.PI; // rads to degs, range (-180, 180]
return Number.isFinite(theta) ? theta : 0;
};
export const angleBetweenPoints = (cx, cy, ex, ey) => {
const dy = ey - cy;
const dx = ex - cx;
let theta = Math.atan2(dy, dx); // range (-PI, PI]
theta *= 180 / Math.PI; // rads to degs, range (-180, 180]
return Number.isFinite(theta) ? theta : 0;
};
export const distance2Point = (x1, y1, x2, y2) => {
const dist = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
return Number.isFinite(dist) ? dist : 0;
};
import { diffDate } from "./diffDate";
import { positiveNumber } from "./positiveNumber";
const xmath = {
rand,
randRound,
randHalt,
randInt,
randFloat,
degToRad,
radToDeg,
degBetweenPoints360,
degBetweenPoints,
angleBetweenPoints,
distance2Point,
diffDate,
positiveNumber,
};
export default xmath;