29 lines
867 B
TypeScript
29 lines
867 B
TypeScript
const MAX_FORMATTER_CACHE_SIZE = 128;
|
|
|
|
export function getCachedFormatter<TFormatter>(
|
|
cache: Map<string, TFormatter>,
|
|
locale: string,
|
|
options: Record<string, unknown>,
|
|
create: (locale: string, options: Record<string, unknown>) => TFormatter
|
|
): TFormatter {
|
|
const key = `${locale}|${stableOptionsKey(options)}`;
|
|
const cached = cache.get(key);
|
|
if (cached) return cached;
|
|
|
|
const formatter = create(locale, options);
|
|
if (cache.size >= MAX_FORMATTER_CACHE_SIZE) {
|
|
const oldestKey = cache.keys().next().value;
|
|
if (oldestKey) cache.delete(oldestKey);
|
|
}
|
|
cache.set(key, formatter);
|
|
return formatter;
|
|
}
|
|
|
|
function stableOptionsKey(options: Record<string, unknown>): string {
|
|
return JSON.stringify(
|
|
Object.entries(options)
|
|
.filter(([, value]) => value !== undefined)
|
|
.sort(([left], [right]) => left.localeCompare(right))
|
|
);
|
|
}
|