typescript 31 lines · 7 steps

Caching Intl.NumberFormat for compact numbers

Format numbers like 1.2K by memoizing costly Intl.NumberFormat instances keyed on their options.

Explained by highlit
1type CompactOptions = {
2 locale?: string;
3 maximumFractionDigits?: number;
4};
5 
6const formatterCache = new Map<string, Intl.NumberFormat>();
7 
8function getFormatter(locale: string, maximumFractionDigits: number): Intl.NumberFormat {
9 const key = `${locale}:${maximumFractionDigits}`;
10 let formatter = formatterCache.get(key);
11 
12 if (!formatter) {
13 formatter = new Intl.NumberFormat(locale, {
14 notation: "compact",
15 compactDisplay: "short",
16 maximumFractionDigits,
17 });
18 formatterCache.set(key, formatter);
19 }
20 
21 return formatter;
22}
23 
24export function formatCompact(value: number, options: CompactOptions = {}): string {
25 if (!Number.isFinite(value)) {
26 throw new RangeError(`Cannot format non-finite value: ${value}`);
27 }
28 
29 const { locale = "en-US", maximumFractionDigits = 1 } = options;
30 return getFormatter(locale, maximumFractionDigits).format(value);
31}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Constructing Intl.NumberFormat is expensive, so caching instances by their config pays off under repeated calls.
  2. 2A composite string key lets a single Map memoize across multiple distinct arguments.
  3. 3Validating inputs at the boundary keeps failures loud and close to their source.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react';
 
const cache = new Map();
const inflight = new Map();

Building a stale-while-revalidate hook in React

caching request-deduplication custom-hooks
Advanced 10 steps
php
<?php
 
namespace App\Services;
 

Building a cached daily leaderboard in Laravel

caching aggregation eager-loading
Intermediate 9 steps

Share this explainer

Here's the card — post it anywhere.

Caching Intl.NumberFormat for compact numbers — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code