Nike | OA | Best Language Match
606

Best Language Match

  • Write a method that accepts a single language key and return the associated translation.
  • If the data doesn't have a translation for the given key, it should attempt to infer the next-best translation based on the passed language key.
  • If the function can't determine a match, it should return null
  • Translation data is as follows -
 const translation = { 
 en: 'Red Color Flyknit', en_GB: 'Red Colour Flyknit',
 fr: 'Couleur Rouge Flyknit', fr_FR: 'France Rouge Flyknit',
 fr_FR_paris: 'France Bleue Flyknit', fr_FR_paris_louvre: 'Louvre France Bleue Flyknit'
 }

Test Cases

const testData = [
   {
   	input: ['en-GB'],
   	output: ['Red Colour Flyknit'],
   },
   {
   	input: ['en_US', 'fr_CA'],
   	output: ['Red Color Flyknit', 'Couleur Rouge Flyknit'],
   },
   {
   	input: ['fr_FR_lyon', 'fr_FR_paris_louvre'],
   	output: ['France Rouge Flyknit', 'Louvre France Bleue Flyknit'],
   },
   {
   	input: ['zh'],
   	output: [null],
   },
]

Solution

function bestLanguageMatch(lang) {
   lang = lang.replace('-', '_')
   const map = {
   	en: 'Red Color Flyknit',
   	en_GB: 'Red Colour Flyknit',
   	fr: 'Couleur Rouge Flyknit',
   	fr_FR: 'France Rouge Flyknit',
   	fr_FR_paris: 'France Bleue Flyknit',
   	fr_FR_paris_louvre: 'Louvre France Bleue Flyknit',
   }

   while (lang) {
   	if (map[lang]) {
   		return map[lang]
   	}
   	lang = lang.split('_')
   	lang.pop()
   	lang = lang.join('_')
   }
   return null
}
Comments (0)