houser-js-utils
Version:
A comprehensive collection of TypeScript utility functions for common development tasks including array manipulation, string processing, date handling, random number generation, validation, and much more.
1 lines • 11.6 kB
Source Map (JSON)
{"version":3,"file":"FormatUtils.mjs","sources":["../src/FormatUtils.ts"],"sourcesContent":["/**\n * @module FormatUtils\n * @description A comprehensive collection of utility functions for formatting data, text, numbers, and dates.\n * @example\n * ```typescript\n * import { FormatUtils } from 'houser-js-utils';\n *\n * // Format phone number\n * const phone = FormatUtils.formatPhoneNumber('1234567890'); // \"(123) 456-7890\"\n *\n * // Format currency\n * const price = FormatUtils.formatCurrency(1234.56); // \"$1,234.56\"\n *\n * // Format file size\n * const size = FormatUtils.formatFileSize(1048576); // \"1.0 MB\"\n * ```\n */\n\nexport const FormatUtils = {\n /**\n * Formats an address into a comma-separated string.\n *\n * @param address - The address object to format\n * @param address.street - Street address\n * @param address.city - City name\n * @param address.state - State or province\n * @param address.zip - ZIP or postal code\n * @param address.country - Country name\n * @returns The formatted address string\n *\n * @example\n * ```typescript\n * const address = {\n * street: \"123 Main St\",\n * city: \"Springfield\",\n * state: \"IL\",\n * zip: \"62701\"\n * };\n * const formatted = FormatUtils.formatAddress(address);\n * // \"123 Main St, Springfield, IL, 62701\"\n * ```\n */\n formatAddress: (address: {\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n country?: string;\n }): string => {\n const parts: string[] = [];\n if (address.street) parts.push(address.street);\n if (address.city) parts.push(address.city);\n if (address.state) parts.push(address.state);\n if (address.zip) parts.push(address.zip);\n if (address.country) parts.push(address.country);\n\n return parts.join(\", \");\n },\n\n /**\n * Formats a credit card number by adding spaces every 4 digits.\n *\n * @param cardNumber - The card number to format\n * @returns The formatted card number with spaces\n *\n * @example\n * ```typescript\n * const card = FormatUtils.formatCreditCard(\"4111111111111111\");\n * // \"4111 1111 1111 1111\"\n * ```\n */\n formatCreditCard: (cardNumber: string): string => {\n const cleaned = cardNumber.replace(/\\D/g, \"\");\n const groups = cleaned.match(/.{1,4}/g);\n return groups ? groups.join(\" \") : cardNumber;\n },\n\n /**\n * Formats a number as currency using the Intl.NumberFormat API.\n *\n * @param amount - The amount to format\n * @param currency - The currency code (e.g., 'USD', 'EUR', 'GBP')\n * @param locale - The locale to use for formatting\n * @returns The formatted currency string\n *\n * @example\n * ```typescript\n * const price = FormatUtils.formatCurrency(99.99, \"USD\", \"en-US\");\n * // \"$99.99\"\n *\n * const euros = FormatUtils.formatCurrency(99.99, \"EUR\", \"de-DE\");\n * // \"99,99 €\"\n * ```\n */\n formatCurrency: (\n amount: number,\n currency = \"USD\",\n locale = \"en-US\"\n ): string => {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n }).format(amount);\n },\n\n /**\n * Formats a file size in bytes to a human-readable string.\n *\n * @param bytes - The size in bytes\n * @param decimals - Number of decimal places to show\n * @returns The formatted file size with appropriate unit\n *\n * @example\n * ```typescript\n * const size = FormatUtils.formatFileSize(1024); // \"1 KB\"\n * const size2 = FormatUtils.formatFileSize(1024 * 1024, 1); // \"1.0 MB\"\n * ```\n */\n formatFileSize: (bytes: number, decimals = 2): string => {\n if (bytes === 0) return \"0 Bytes\";\n\n const k = 1024;\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${\n sizes[i]\n }`;\n },\n\n /**\n * Formats a number with commas as thousands separators.\n *\n * @param num - Number to format\n * @returns Formatted number string with commas\n *\n * @example\n * ```typescript\n * const num = FormatUtils.formatNumber(1000000); // \"1,000,000\"\n * ```\n */\n formatNumber: (num: number): string => {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n },\n\n /**\n * Formats a number as a percentage.\n *\n * @param value - The value to format\n * @param decimals - Number of decimal places to show\n * @returns The formatted percentage string\n *\n * @example\n * ```typescript\n * const percent = FormatUtils.formatPercent(75.5); // \"75.5%\"\n * ```\n */\n formatPercent: (value: number, decimals = 1): string => {\n return `${value.toFixed(decimals)}%`;\n },\n\n /**\n * Formats a phone number according to the specified format.\n *\n * @param phone - The phone number to format\n * @param format - The format to use ('US' or 'EU')\n * @returns The formatted phone number\n *\n * @example\n * ```typescript\n * const usPhone = FormatUtils.formatPhoneNumber(\"1234567890\", \"US\");\n * // \"(123) 456-7890\"\n *\n * const euPhone = FormatUtils.formatPhoneNumber(\"1234567890\", \"EU\");\n * // \"12 34 56 78 90\"\n * ```\n */\n formatPhoneNumber: (phone: string, format: \"US\" | \"EU\" = \"US\"): string => {\n const cleaned = phone.replace(/\\D/g, \"\");\n\n if (format === \"US\") {\n const match = cleaned.match(/^(\\d{3})(\\d{3})(\\d{4})$/);\n if (match) {\n return `(${match[1]}) ${match[2]}-${match[3]}`;\n }\n } else if (format === \"EU\") {\n const match = cleaned.match(/^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})$/);\n if (match) {\n return `${match[1]} ${match[2]} ${match[3]} ${match[4]} ${match[5]}`;\n }\n }\n\n return phone;\n },\n\n /**\n * Formats a duration in milliseconds to a human-readable string.\n *\n * @param ms - The duration in milliseconds\n * @param format - The format to use ('short' or 'long')\n * @returns The formatted duration string\n *\n * @example\n * ```typescript\n * const short = FormatUtils.formatDuration(3661000, \"short\"); // \"1h\"\n * const long = FormatUtils.formatDuration(3661000, \"long\");\n * // \"1 hour, 1 minute, 1 second\"\n * ```\n */\n formatDuration: (ms: number, format: \"short\" | \"long\" = \"short\"): string => {\n if (ms === 0) return format === \"short\" ? \"0s\" : \"0 seconds\";\n\n const seconds = Math.floor(ms / 1000);\n const minutes = Math.floor(seconds / 60);\n const hours = Math.floor(minutes / 60);\n const days = Math.floor(hours / 24);\n\n // For short format, return the largest non-zero unit\n if (format === \"short\") {\n if (days > 0) return `${days}d`;\n if (hours > 0) return `${hours}h`;\n if (minutes > 0) return `${minutes}m`;\n return `${seconds}s`;\n }\n\n // For long format, calculate remaining time after each unit\n const remainingSeconds = seconds % 60;\n const remainingMinutes = minutes % 60;\n const remainingHours = hours % 24;\n\n const parts: string[] = [];\n\n if (days > 0) {\n parts.push(`${days} day${days === 1 ? \"\" : \"s\"}`);\n }\n if (remainingHours > 0) {\n parts.push(`${remainingHours} hour${remainingHours === 1 ? \"\" : \"s\"}`);\n }\n if (remainingMinutes > 0) {\n parts.push(\n `${remainingMinutes} minute${remainingMinutes === 1 ? \"\" : \"s\"}`\n );\n }\n if (remainingSeconds > 0) {\n parts.push(\n `${remainingSeconds} second${remainingSeconds === 1 ? \"\" : \"s\"}`\n );\n }\n\n return parts.join(\", \");\n },\n\n /**\n * Formats a social security number with hyphens.\n *\n * @param ssn - The SSN to format\n * @returns The formatted SSN\n *\n * @example\n * ```typescript\n * const ssn = FormatUtils.formatSSN(\"123456789\"); // \"123-45-6789\"\n * ```\n */\n formatSSN: (ssn: string): string => {\n const cleaned = ssn.replace(/\\D/g, \"\");\n const match = cleaned.match(/^(\\d{3})(\\d{2})(\\d{4})$/);\n return match ? `${match[1]}-${match[2]}-${match[3]}` : ssn;\n },\n};\n"],"names":[],"mappings":"AAkBO,MAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBzB,eAAe,CAAC,YAMF;AACZ,UAAM,QAAkB,CAAA;AACxB,QAAI,QAAQ,OAAQ,OAAM,KAAK,QAAQ,MAAM;AAC7C,QAAI,QAAQ,KAAM,OAAM,KAAK,QAAQ,IAAI;AACzC,QAAI,QAAQ,MAAO,OAAM,KAAK,QAAQ,KAAK;AAC3C,QAAI,QAAQ,IAAK,OAAM,KAAK,QAAQ,GAAG;AACvC,QAAI,QAAQ,QAAS,OAAM,KAAK,QAAQ,OAAO;AAE/C,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB;AAAA;AAAA;AAAA;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