UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

50 lines (49 loc) 1.83 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getOrdinal = exports.getRandomFloat = exports.clampNumber = exports.formatCurrency = exports.roundToNearest = void 0; exports.normalizeNumber = normalizeNumber; const primitives_1 = require("../guards/primitives"); const specials_1 = require("../guards/specials"); const constants_1 = require("./constants"); const roundToNearest = (value, interval = 5) => { return Math.round(Number(value) / interval) * interval; }; exports.roundToNearest = roundToNearest; const formatCurrency = (value, currency = 'USD', locale) => { const selectedLocale = locale ? locale : constants_1.CURRENCY_LOCALES[currency]; return new Intl.NumberFormat(selectedLocale, { style: 'currency', currency, }).format(value); }; exports.formatCurrency = formatCurrency; const clampNumber = (value, min, max) => { return Math.max(min, Math.min(value, max)); }; exports.clampNumber = clampNumber; const getRandomFloat = (min, max) => { return Math.random() * (Number(max) - Number(min)) + Number(min); }; exports.getRandomFloat = getRandomFloat; 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; }; exports.getOrdinal = getOrdinal; function normalizeNumber(num) { return (0, primitives_1.isNumber)(num) ? num : (0, specials_1.isNumericString)(num) ? Number(num) : undefined; }