feat(Text to NATO): add other languages, upper/lower and other

Add support for many languages and countries ((International), (France), (Belgium), (Switzerland), (Québec), (Germany, 2022), (Austria), (Germany, informal, 2022), (Netherlands), Italian, Spanish, (Brazil), (Portugal), Swedish, Danish, Norwegian, Finnish, Turkish, Romanian, Czech, Yugoslav, Serbian, Slovene, Russian, Korean, Greek, Japanese)
Handle uppercase/lowercase and some punctuations
Fix #794
This commit is contained in:
sharevb 2024-04-02 08:57:13 +02:00 committed by ShareVB
parent d3b32cc14e
commit 1b1be10762
4 changed files with 1644 additions and 42 deletions

View file

@ -1,19 +1,32 @@
import { natoAlphabet } from './text-to-nato-alphabet.constants';
import allAlphabets from './nato.alphabets.json';
type AllALphabetsKeys = keyof typeof allAlphabets[0];
export { textToNatoAlphabet };
function getLetterPositionInAlphabet({ letter }: { letter: string }) {
return letter.toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0);
}
function textToNatoAlphabet({ text }: { text: string }) {
function textToNatoAlphabet({ text, langOrCountry = '(International)' }: { text: string; langOrCountry: string }) {
const charRegex = new RegExp(
`(${
allAlphabets
.sort((a, b) => b.Letter.length - a.Letter.length)
.filter(a => a[langOrCountry as AllALphabetsKeys])
.map(a => a.Letter)
.join('|')
}|.)`,
'gi');
return text
.split('')
.map((character) => {
const alphabetIndex = getLetterPositionInAlphabet({ letter: character });
const natoWord = natoAlphabet[alphabetIndex];
.replace(/\s/g, ' ')
.replace(
charRegex,
(character) => {
const searchChar = character.toUpperCase();
const isUpper = character[0].toUpperCase() === character[0];
const alphabetLetter = allAlphabets.find(letter => letter.Letter === searchChar);
if (alphabetLetter && alphabetLetter[langOrCountry as AllALphabetsKeys]) {
const natoWord = alphabetLetter[langOrCountry as AllALphabetsKeys] || '';
return ` ${isUpper ? natoWord.toUpperCase() : natoWord.toLowerCase()} `;
}
return natoWord ?? character;
})
.join(' ');
return ` (${character}) `;
});
}