Files
wdi-dashboard/node_modules/@chakra-ui/number-utils/dist/index.mjs
2024-08-16 15:06:52 +05:30

50 lines
1.3 KiB
JavaScript

// src/index.ts
function toNumber(value) {
const num = parseFloat(value);
return typeof num !== "number" || Number.isNaN(num) ? 0 : num;
}
function toPrecision(value, precision) {
let nextValue = toNumber(value);
const scaleFactor = 10 ** (precision != null ? precision : 10);
nextValue = Math.round(nextValue * scaleFactor) / scaleFactor;
return precision ? nextValue.toFixed(precision) : nextValue.toString();
}
function countDecimalPlaces(value) {
if (!Number.isFinite(value))
return 0;
let e = 1;
let p = 0;
while (Math.round(value * e) / e !== value) {
e *= 10;
p += 1;
}
return p;
}
function valueToPercent(value, min, max) {
return (value - min) * 100 / (max - min);
}
function percentToValue(percent, min, max) {
return (max - min) * percent + min;
}
function roundValueToStep(value, from, step) {
const nextValue = Math.round((value - from) / step) * step + from;
const precision = countDecimalPlaces(step);
return toPrecision(nextValue, precision);
}
function clampValue(value, min, max) {
if (value == null)
return value;
if (max < min) {
console.warn("clamp: max cannot be less than min");
}
return Math.min(Math.max(value, min), max);
}
export {
clampValue,
countDecimalPlaces,
percentToValue,
roundValueToStep,
toPrecision,
valueToPercent
};