Skip to content

Instantly share code, notes, and snippets.

@outadoc
Created February 26, 2021 17:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save outadoc/ab3b8da157748183d4afca5de4a26a54 to your computer and use it in GitHub Desktop.
Save outadoc/ab3b8da157748183d4afca5de4a26a54 to your computer and use it in GitHub Desktop.
Country code to Unicode flag emoji in Kotlin
/**
* 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