UNPKG

camote-utils

Version:

A comprehensive TypeScript utility library featuring advanced string and number formatting, data structures, and algorithms

75 lines (74 loc) 2.92 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calculateDiscountPrice = exports.formatDecimals = exports.formatCurrency = exports.formatFileSize = exports.formatOrdinal = exports.formatPercentage = exports.formatWithCommas = exports.humanReadableNumber = void 0; const humanReadableNumber = (num, options) => { const { decimals = 1, compact = false } = options || {}; if (num < 1000) return Math.floor(num).toString(); const units = ['K', 'M', 'B', 'T']; const order = Math.floor(Math.log10(num) / 3); const unitName = units[order - 1]; const formattedNum = (num / Math.pow(1000, order)).toFixed(compact ? 1 : decimals); return decimals === 0 ? `${parseInt(formattedNum)}${unitName}` : `${formattedNum}${unitName}`; }; exports.humanReadableNumber = humanReadableNumber; const formatWithCommas = (num) => { return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }; exports.formatWithCommas = formatWithCommas; const formatPercentage = (num, decimals = 0) => { return `${(num * 100).toFixed(decimals)}%`; }; exports.formatPercentage = formatPercentage; const formatOrdinal = (num) => { const j = num % 10; const k = num % 100; if (j === 1 && k !== 11) return num + "st"; if (j === 2 && k !== 12) return num + "nd"; if (j === 3 && k !== 13) return num + "rd"; return num + "th"; }; exports.formatOrdinal = formatOrdinal; const formatFileSize = (bytes, decimals = 2) => { if (bytes === 0) return "0 Bytes"; const k = 1024; const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"]; const i = Math.floor(Math.log(bytes) / Math.log(k)); const value = bytes / Math.pow(k, i); return `${value.toFixed(i > 0 ? decimals : 0)} ${sizes[i]}`; }; exports.formatFileSize = formatFileSize; const formatCurrency = (amount, currency = 'USD', locale = 'en-US') => { return new Intl.NumberFormat(locale, { style: 'currency', currency: currency }).format(amount); }; exports.formatCurrency = formatCurrency; const formatDecimals = (num, decimals, roundingMode = 'round') => { const factor = Math.pow(10, decimals); let result; switch (roundingMode) { case 'ceil': result = Math.ceil(num * factor) / factor; break; case 'floor': result = Math.floor(num * factor) / factor; break; default: result = Math.round(num * factor) / factor; } return result.toFixed(decimals); }; exports.formatDecimals = formatDecimals; const calculateDiscountPrice = (originalPrice, discountAmount, discountType = '%') => { const discountValue = discountType === '$' ? discountAmount : originalPrice * (discountAmount / 100); return parseFloat((originalPrice - discountValue).toFixed(2)); }; exports.calculateDiscountPrice = calculateDiscountPrice;