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
const express = require('express'); const app = express();
Enforcing HTTPS with Express middleware
middleware
https
security
Intermediate
6 steps
ruby
module Rack class MaintenanceMode RETRY_AFTER = 3600
A Rack maintenance-mode middleware in Rails
middleware
rack
http-status
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 steps
javascript
function parseHexColor(hex) { const cleaned = hex.trim().replace(/^#/, ''); const expand = (short) =>
Parsing hex colors into RGBA channels
parsing
bitwise
regex
Intermediate
7 steps
javascript
import { useReducer, useCallback } from 'react'; function historyReducer(state, action) { const { past, present, future } = state;
Undo/redo form state with a React reducer
undo-redo
reducer
immutability
Intermediate
10 steps
javascript
import { NextResponse } from 'next/server'; import { db } from '@/lib/db'; function csvCell(value) {
Streaming a CSV export in a Next.js route
streaming
csv
readablestream
Advanced
9 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.