Created
February 26, 2021 17:48
-
-
Save outadoc/ab3b8da157748183d4afca5de4a26a54 to your computer and use it in GitHub Desktop.
Country code to Unicode flag emoji in Kotlin
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
/** | |
* Converts an ISO 3166-1 alpha-2 country code to the corresponding Unicode flag emoji. | |
* | |
* ``` | |
* "FR".countryCodeToUnicodeFlag() // 🇫🇷 | |
* "US".countryCodeToUnicodeFlag() // 🇺🇸 | |
* ``` | |
*/ | |
fun String.countryCodeToUnicodeFlag(): String { | |
return this | |
.filter { it in 'A'..'Z' } | |
.map { it.toByte() } | |
.flatMap { char -> | |
listOf( | |
// First UTF-16 char is \uD83C | |
0xD8.toByte(), | |
0x3C.toByte(), | |
// Second char is \uDDE6 for A and increments from there | |
0xDD.toByte(), | |
(0xE6.toByte() + (char - 'A'.toByte())).toByte() | |
) | |
} | |
.toByteArray() | |
.let { bytes -> | |
String(bytes, Charsets.UTF_16) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment