Skip to content

Commit db8dcc3

Browse files
committed
fix(perf): single translation lookup for each doc
It's faster to get translations including all region codes and filter them, rather than get translations twice, once with a region code and once without.
1 parent 161e2cc commit db8dcc3

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

src/datatype/index.js

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -288,26 +288,34 @@ export class DataType extends TypedEmitter {
288288
const { language, region } = parseBCP47(lang)
289289
if (!language) return doc
290290

291-
const value = {
291+
const translations = await this.#getTranslations({
292292
languageCode: language,
293293
docRef: {
294294
docId: doc.docId,
295295
versionId: doc.versionId,
296296
},
297297
docRefType: doc.schemaName,
298-
regionCode: region !== null ? region : undefined,
299-
}
300-
let translations = await this.#getTranslations(value)
301-
// if passing a region code returns no matches,
302-
// fallback to matching only languageCode
303-
if (translations.length === 0 && value.regionCode) {
304-
value.regionCode = undefined
305-
translations = await this.#getTranslations(value)
306-
}
298+
})
307299

300+
/** @type {Set<string>} */
301+
const translationsWithMatchingRegion = new Set()
308302
for (const translation of translations) {
309303
if (typeof getProperty(doc, translation.propertyRef) === 'string') {
310-
setProperty(doc, translation.propertyRef, translation.message)
304+
const isMatchingRegion = region
305+
? translation.regionCode === region
306+
: false
307+
// Prefer translations with a matching region code, but fall back to
308+
// translations without a region code if no matching region code has
309+
// been found yet for this propertyRef
310+
if (
311+
isMatchingRegion ||
312+
!translationsWithMatchingRegion.has(translation.propertyRef)
313+
) {
314+
setProperty(doc, translation.propertyRef, translation.message)
315+
}
316+
if (isMatchingRegion) {
317+
translationsWithMatchingRegion.add(translation.propertyRef)
318+
}
311319
}
312320
}
313321

0 commit comments

Comments
 (0)