javascript
34 lines · 8 steps
Caching Intl.NumberFormat for currency formatting
A memoized factory reuses expensive Intl.NumberFormat instances to format currency, cents, and ranges.
Explained by
highlit
1const formatters = new Map();
2
3function getFormatter(locale, currency) {
4 const key = `${locale}:${currency}`;
5 let formatter = formatters.get(key);
6
7 if (!formatter) {
8 formatter = new Intl.NumberFormat(locale, {
9 style: 'currency',
10 currency,
11 currencyDisplay: 'symbol',
12 });
13 formatters.set(key, formatter);
14 }
15
16 return formatter;
17}
18
19export function formatCurrency(amount, { locale = 'en-US', currency = 'USD' } = {}) {
20 if (amount == null || Number.isNaN(amount)) {
21 return '';
22 }
23
24 return getFormatter(locale, currency).format(amount);
25}
26
27export function formatFromCents(cents, options = {}) {
28 return formatCurrency(cents / 100, options);
29}
30
31export function formatRange(min, max, options = {}) {
32 const formatter = getFormatter(options.locale ?? 'en-US', options.currency ?? 'USD');
33 return formatter.formatRange(min, max);
34}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Constructing Intl formatters is costly, so caching them by their configuration avoids repeated setup.
- 2A composite string key lets a single Map memoize across multiple independent parameters.
- 3Sharing one cached formatter behind several public helpers keeps behavior consistent and cheap.
Related explainers
javascript
import { NextResponse } from 'next/server' const UPSTREAM = 'https://api.exchangerate.host/latest'
A cached exchange-rate proxy in Next.js
route-handler
caching
revalidation
Intermediate
7 steps
javascript
const logger = require('./logger'); class AppError extends Error { constructor(message, statusCode = 500, details = null) {
Centralized error handling in Express
error-handling
middleware
custom-errors
Intermediate
8 steps
javascript
class DOMBatcher { constructor() { this.reads = []; this.writes = [];
Batching DOM reads and writes to avoid layout thrash
batching
requestanimationframe
layout-thrashing
Intermediate
8 steps
go
package web import ( "embed"
Serving embedded static assets in Go
embed
static-assets
http-handler
Intermediate
8 steps
javascript
function createCountdownTimer(durationSeconds, { onTick, onComplete } = {}) { let remaining = durationSeconds; let intervalId = null;
Building a countdown timer with closures
closures
factory-function
timers
Intermediate
9 steps
javascript
export function buildPaginationUrl(baseUrl, { page, perPage, filters = {}, sort } = {}) { const url = new URL(baseUrl); const params = url.searchParams;
Building and parsing pagination URLs
url-parsing
query-string
pagination
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/caching-intl-numberformat-for-currency-formatting-explained-javascript-6321/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.