Skip to content

Instantly share code, notes, and snippets.

@rock3r
Last active February 7, 2023 17:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rock3r/a2caf6b8a056982c8ab8ea1429d36ab6 to your computer and use it in GitHub Desktop.
Save rock3r/a2caf6b8a056982c8ab8ea1429d36ab6 to your computer and use it in GitHub Desktop.
A Kotlin script to normalize hex colour representations ("#RGB", "#ARGB", "#RRGGBB", "#AARRGGBB") into "#AARRGGBB", useful for when you're trying to find all unique colours in your app
/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* Sebastiano Poggi wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Seb
* ----------------------------------------------------------------------------
* Feel free to attribute this code in compiled products if you feel like it,
* but it's not required.
*/
import java.util.Locale
import kotlin.text.toRegex
private val colorHexRegex = "#?([0-9a-f]{3,8})".toRegex(RegexOption.IGNORE_CASE)
fun normalizeColorHex(colorHex: String): String {
val matchResult = colorHexRegex.matchEntire(colorHex)
?: throw IllegalArgumentException("The provided colorHex '$colorHex' is not a valid color hex")
val hexValue = matchResult.groups[1]!!.value.toLowerCase(Locale.US)
val normalizedArgb = when (hexValue.length) {
3 -> expandToTwoDigitsPerComponent("f$hexValue")
4 -> expandToTwoDigitsPerComponent(hexValue)
6 -> "ff$hexValue"
8 -> hexValue
else -> throw IllegalArgumentException("The provided colorHex '$colorHex' is not in a supported format")
}
return "#$normalizedArgb"
}
fun expandToTwoDigitsPerComponent(hexValue: String) =
hexValue.asSequence()
.map { "$it$it" }
.reduce { accumulatedHex, component -> accumulatedHex + component }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment