Created
February 28, 2020 16:23
-
-
Save ashour/9ef84ddd005e16f6262ddcd8d88eddf7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export const defaultLang = "en"; | |
| export const supportedLangs = { | |
| en: "English", | |
| ar: "Arabic (عربي)", | |
| }; | |
| export function determineUserLang(acceptedLangs, path = null) { | |
| // check url for /en/foo where en is a supported language code | |
| if (path !== null) { | |
| const urlLang = path.trim().split("/")[1]; | |
| const matchingUrlLang = findFirstSupported([stripCountry(urlLang)]); | |
| if (matchingUrlLang) { | |
| return matchingUrlLang; | |
| } | |
| } | |
| // check browser-set accepted langs | |
| const matchingAcceptedLang = findFirstSupported( | |
| acceptedLangs.map(stripCountry), | |
| ); | |
| return matchingAcceptedLang || defaultLang; | |
| } | |
| function findFirstSupported(langs) { | |
| const supported = Object.keys(supportedLangs); | |
| return langs.find(code => supported.includes(code)); | |
| } | |
| function stripCountry(lang) { | |
| return lang | |
| .trim() | |
| .replace("_", "-") | |
| .split("-")[0]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment