diff --git a/fluent/src/context.js b/fluent/src/context.js index 1cbdb9a2a..4de3c59af 100644 --- a/fluent/src/context.js +++ b/fluent/src/context.js @@ -1,5 +1,6 @@ import resolve from "./resolver"; import FluentResource from "./resource"; +import IntlMemoizer from "./intl_memoizer"; /** * Message contexts are single-language stores of translations. They are @@ -52,7 +53,8 @@ export class MessageContext { constructor(locales, { functions = {}, useIsolating = true, - transform = v => v + transform = v => v, + intlMemoizer = new IntlMemoizer(), } = {}) { this.locales = Array.isArray(locales) ? locales : [locales]; @@ -61,7 +63,7 @@ export class MessageContext { this._functions = functions; this._useIsolating = useIsolating; this._transform = transform; - this._intls = new WeakMap(); + this._intlMemoizer = intlMemoizer; } /* @@ -210,14 +212,6 @@ export class MessageContext { } _memoizeIntlObject(ctor, opts) { - const cache = this._intls.get(ctor) || {}; - const id = JSON.stringify(opts); - - if (!cache[id]) { - cache[id] = new ctor(this.locales, opts); - this._intls.set(ctor, cache); - } - - return cache[id]; + return this._intlMemoizer.get(ctor, this.locales, opts); } } diff --git a/fluent/src/intl_memoizer.js b/fluent/src/intl_memoizer.js new file mode 100644 index 000000000..8052232e7 --- /dev/null +++ b/fluent/src/intl_memoizer.js @@ -0,0 +1,17 @@ +export default class IntlMemoizer { + constructor() { + this._intls = new WeakMap(); + } + + get(ctor, locales, opts) { + const cache = this._intls.get(ctor) || new Map(); + const id = {locales, ...opts}; + + if (!cache.has(id)) { + cache.set(id, new ctor(locales, opts)); + this._intls.set(ctor, cache); + } + + return cache.get(id); + } +}