Created
April 24, 2025 17:42
-
-
Save dejurin/d31925498c7f95499f13887bb30c6cf9 to your computer and use it in GitHub Desktop.
A lightweight, DRY wrapper for Intl.NumberFormat with built-in formatter caching and flexible options.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Formatting options for prettyNumber. | |
* Extends all standard Intl.NumberFormatOptions and adds an optional locale override. | |
*/ | |
export interface PrettyNumberOptions extends Intl.NumberFormatOptions { | |
/** BCP 47 language tag, e.g. 'en-US', 'ru-RU'. Defaults to 'en-US'. */ | |
locale?: string; | |
} | |
/** Cache key → Intl.NumberFormat instance */ | |
const formatterCache = new Map<string, Intl.NumberFormat>(); | |
/** | |
* Retrieves a cached Intl.NumberFormat or creates a new one if not present. | |
* | |
* @param options - Formatting options including locale and Intl.NumberFormatOptions. | |
* @returns Intl.NumberFormat instance configured per options. | |
*/ | |
function getFormatter(options: PrettyNumberOptions = {}): Intl.NumberFormat { | |
const { locale = "en-US", ...nfOptions } = options; | |
const cacheKey = JSON.stringify({ locale, ...nfOptions }); | |
if (!formatterCache.has(cacheKey)) { | |
formatterCache.set(cacheKey, new Intl.NumberFormat(locale, nfOptions)); | |
} | |
return formatterCache.get(cacheKey)!; | |
} | |
/** | |
* Formats a number according to the specified locale and formatting options. | |
* | |
* @param value - Numeric value to format. | |
* @param options - Optional formatting settings (locale, style, notation, etc.). | |
* @returns Formatted number string. | |
* | |
* @example | |
* prettyNumber(1234); // "1,234" (default en-US) | |
* prettyNumber(0.1234, { style: 'percent', minimumFractionDigits: 1 }); // "12.3%" | |
* prettyNumber(1234567, { notation: 'compact', compactDisplay: 'short', locale: 'ru-RU' }); // "1,2 млн" | |
*/ | |
export function prettyNumber( | |
value: number, | |
options?: PrettyNumberOptions | |
): string { | |
return getFormatter(options).format(value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment