in packages/babel-plugin-fbt/src/translate/TranslationBuilder.js [451:514]
function _createMemoizedConstraintMapGetter(
instance: TranslationBuilder,
): (hash: PatternHash) => ConstraintKeyToTranslation {
// Yes this is hand-rolled memoization :(
// TODO: T37795723 - Pull in a lightweight (not bloated) memoization library
const _mem = {};
return function getConstraintMap(
hash: PatternHash,
): ConstraintKeyToTranslation {
if (_mem[hash]) {
return _mem[hash];
}
const constraintMap = {};
const transData = this._translations[hash];
if (transData == null || typeof transData === 'string') {
// No translation? No constraints.
return (_mem[hash] = constraintMap);
}
// For every possible variation combination, create a mapping to its
// corresponding translation
transData.translations.forEach(translation => {
const constraints = {};
for (const idx in translation.variations) {
const variation = translation.variations[idx];
// We prune entries that contain non-default variations
// for tokens we haven't specified.
const token = transData.tokens[Number(idx)];
if (
// Token variation type not specified
!this._tokenToMask[token] ||
// Translated variation type is different than token variation type
this._tokenToMask[token] !== transData.types[Number(idx)]
) {
// Only add default tokens we haven't specified.
if (!this._config.isDefaultVariation(variation)) {
return;
}
}
constraints[token] = variation;
}
// A note about fbt:plurals. They can introduce global token
// discrepancies between leaf nodes. Singular translations don't have
// number tokens, but their plural counterparts can (when showCount =
// "ifMany" or "yes"). If we are dealing with the singular leaf of an
// fbt:plural, since it has a unique hash, we can let it masquerade as
// default: '*', since no such variation actually exists for a
// non-existent token
const constraintKeys = [];
for (const k in this._tokenToMask) {
constraintKeys.push([k, constraints[k] || '*']);
}
this._insertConstraint(
constraintKeys,
constraintMap,
translation.translation,
0,
);
});
return (_mem[hash] = constraintMap);
}.bind(instance);
}