chore: better path getter func

This commit is contained in:
Lewis Crichton 2024-06-11 22:25:09 +01:00
parent 26c21c2de8
commit 8c4aed699d
No known key found for this signature in database
2 changed files with 6 additions and 18 deletions

View file

@ -116,16 +116,10 @@ async function getTranslation(node: Node): Promise<string | null> {
await readFile(`./translations/en/${namespace}.json`, "utf-8") await readFile(`./translations/en/${namespace}.json`, "utf-8")
); );
function getByPath(key: string, object: any) { const dotProp = (key: string, object: any) =>
try { key.split(".").reduce((obj, key) => obj?.[key], object);
return key.split(".").reduce((obj, key) => obj[key], object);
} catch {
// errors if the object doesn't contain the key
return undefined;
}
}
return getByPath(path, bundle); return dotProp(path, bundle);
} }
async function parseFile(fileName: string) { async function parseFile(fileName: string) {

View file

@ -74,20 +74,14 @@ function format(source: string, variables: Record<string, any>) {
} }
// converts a dot-notation path to an object value // converts a dot-notation path to an object value
function getByPath(key: string, object: any) { const dotProp = (key: string, object: any) =>
try { key.split(".").reduce((obj, key) => obj?.[key], object);
return key.split(".").reduce((obj, key) => obj[key], object);
} catch {
// errors if the object doesn't contain the key
return undefined;
}
}
type Translation = string | ({ [rule in Intl.LDMLPluralRule]?: string } & { other: string; }); type Translation = string | ({ [rule in Intl.LDMLPluralRule]?: string } & { other: string; });
// translation retrieval function // translation retrieval function
function _t(key: string, bundle: any): Translation { function _t(key: string, bundle: any): Translation {
const translation = getByPath(key, bundle); const translation = dotProp(key, bundle);
if (!translation) { if (!translation) {
if (bundle !== translations.en) { if (bundle !== translations.en) {