Last active
March 24, 2021 20:30
-
-
Save brianfoshee/ce7712fb199b3e32f462b163f937ebae to your computer and use it in GitHub Desktop.
Generate a Country's Flag Emoji given its 2 letter Country Code
This file contains 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
// Generate a Country's Flag Emoji given its 2 letter Country Code | |
// https://emojipedia.org/flags/ | |
function flagEmojiFromCountryCode(code) { | |
if (code.length != 2) { | |
// Must be ISO 3166-1 alpha-2 | |
throw new Error(`Country Code "${code}" must be 2 characters`); | |
} | |
var base = 0x1F1E6 // hex of unicode code point for 🇦, "Regional Indicator Symbol Letter A" | |
var a = 'a'.charCodeAt(0) // => 97. Used for calculating unicode offsets from base. | |
var offset1 = code.toLowerCase().charCodeAt(0) - a // first character of the country code's offset from a | |
var offset2 = code.toLowerCase().charCodeAt(1) - a // second character of the country code's offset from a | |
// generate "Regional Indicator Symbol Letter" for each character in the country code | |
// https://emojipedia.org/flag-united-states/ | |
var char1 = String.fromCodePoint(base+offset1) // first unicode code point for flag | |
var char2 = String.fromCodePoint(base+offset2) // second unicode code point for flag | |
return `${char1}${char2}` // combine unicode code points to make the flag emoji | |
} | |
var flag = flagEmojiFromCountryCode('US') | |
console.log(flag) // => 🇺🇸 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment