nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
41 lines (40 loc) • 1.4 kB
JavaScript
import { isNumber } from '../guards/primitives.js';
import { isNumericString } from '../guards/specials.js';
import { CURRENCY_LOCALES } from './constants.js';
export const roundToNearest = (value, interval = 5) => {
return Math.round(Number(value) / interval) * interval;
};
export const formatCurrency = (value, currency = 'USD', locale) => {
const selectedLocale = locale ? locale : CURRENCY_LOCALES[currency];
return new Intl.NumberFormat(selectedLocale, {
style: 'currency',
currency,
}).format(value);
};
export const clampNumber = (value, min, max) => {
return Math.max(min, Math.min(value, max));
};
export const getRandomFloat = (min, max) => {
return Math.random() * (Number(max) - Number(min)) + Number(min);
};
export const getOrdinal = (num, withNumber = true) => {
const remainder10 = Number(num) % 10;
const remainder100 = Number(num) % 100;
let suffix;
if (remainder10 === 1 && remainder100 !== 11) {
suffix = 'st';
}
else if (remainder10 === 2 && remainder100 !== 12) {
suffix = 'nd';
}
else if (remainder10 === 3 && remainder100 !== 13) {
suffix = 'rd';
}
else {
suffix = 'th';
}
return withNumber ? String(num).concat(suffix) : suffix;
};
export function normalizeNumber(num) {
return isNumber(num) ? num : isNumericString(num) ? Number(num) : undefined;
}