@intlayer/core
Version:
Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.
56 lines (54 loc) • 1.85 kB
JavaScript
import { Locales } from "@intlayer/types";
//#region src/utils/intl.ts
/**
* Optimized Cache Key Generator
* 1. Fast path: If no options, just use the locale string.
* 2. Normal path: JSON.stringify for deterministic object comparison.
*/
const getCacheKey = (locales, options) => {
const localeKey = locales ? String(locales) : Locales.ENGLISH;
if (!options) return localeKey;
return `${localeKey}|${JSON.stringify(options)}`;
};
/**
* Generic wrapper for any `new Intl.*()` constructor.
*/
const createCachedConstructor = (Ctor) => {
const cache = /* @__PURE__ */ new Map();
const MAX_CACHE_SIZE = 50;
function Wrapped(locales, options) {
if (Ctor.name === "DisplayNames" && typeof Intl?.DisplayNames !== "function") return locales;
const key = getCacheKey(locales, options);
let instance = cache.get(key);
if (instance) return instance;
instance = new Ctor(locales, options);
if (cache.size >= MAX_CACHE_SIZE) {
const oldestKey = cache.keys().next().value;
if (oldestKey) cache.delete(oldestKey);
}
cache.set(key, instance);
return instance;
}
Wrapped.prototype = Ctor.prototype;
return Wrapped;
};
/**
* Factory that turns the global `Intl` into a cached clone.
*/
const createCachedIntl = () => {
const constructorCache = /* @__PURE__ */ new Map();
return new Proxy(Intl, { get: (target, prop, receiver) => {
if (constructorCache.has(prop)) return constructorCache.get(prop);
const value = Reflect.get(target, prop, receiver);
if (typeof value === "function" && typeof prop === "string" && /^[A-Z]/.test(prop)) {
const wrapped = createCachedConstructor(value);
constructorCache.set(prop, wrapped);
return wrapped;
}
return value;
} });
};
const CachedIntl = createCachedIntl();
//#endregion
export { CachedIntl, CachedIntl as Intl, createCachedIntl };
//# sourceMappingURL=intl.mjs.map