Files
LingvAI/utils/language.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

import languagesJson from "./languages.json";
const { languages, exceptions, mappings } = languagesJson;
2021-03-10 21:31:50 +01:00
const checkTypes = {
exception: exceptions,
mapping: mappings
2021-03-13 19:37:44 +01:00
};
2021-03-10 21:31:50 +01:00
2021-03-13 19:37:44 +01:00
export type CheckType = keyof typeof checkTypes;
2021-03-10 21:31:50 +01:00
2021-03-12 19:41:20 +01:00
const langTypes = [
2021-03-10 21:31:50 +01:00
"source",
"target"
] as const;
2021-03-13 19:37:44 +01:00
export type LangType = typeof langTypes[number];
2021-03-10 21:31:50 +01:00
const isKeyOf = <T extends object>(obj: T) => (key: keyof any): key is keyof T => key in obj;
export function replaceBoth(
checkType: CheckType,
langs: {
[key in LangType]: string
}
): {
[key in LangType]: string
} {
const [source, target] = langTypes.map(langType => {
const object = checkTypes[checkType][langType];
const langCode = langs[langType];
return isKeyOf(object)(langCode) ? object[langCode] : langCode;
});
return { source, target };
}
export function retrieveFromType(type?: LangType): [string, string][] {
const langEntries = Object.entries(languages);
if (!type)
return langEntries;
return langEntries.filter(([code]) => (
!Object.keys(exceptions[type]).includes(code)
2021-03-10 21:31:50 +01:00
));
}
export function getName(code: string): string | null {
return isKeyOf(languages)(code) ? languages[code] : null;
2021-03-10 21:31:50 +01:00
}