Skip to content

Instantly share code, notes, and snippets.

@toe-lie
Created December 1, 2022 13:06
Show Gist options
  • Save toe-lie/79d4dd1541c7ad488bd6751645a41b56 to your computer and use it in GitHub Desktop.
Save toe-lie/79d4dd1541c7ad488bd6751645a41b56 to your computer and use it in GitHub Desktop.
Normalize Color String
private fun normalizeColor(colorString: String?): String? {
if (colorString.isNullOrEmpty()) {
return null
}
if (isInvalidColor(colorString)) {
return null
}
return if (isValidColorByLength(colorString)) {
colorString
} else {
val start = colorString.length.minus(6)
val normalizedColor = colorString.substring(start)
"#$normalizedColor"
}
}
private fun isInvalidColor(
colorString: String
): Boolean {
val minimumValidColorLengthWithHash = 7
val maximumValidColorLengthWithHash = 9
val colorStringLength = colorString.length
return !colorString.startsWith("#") ||
colorStringLength < minimumValidColorLengthWithHash ||
colorStringLength > maximumValidColorLengthWithHash
}
private fun isValidColorByLength(colorString: String): Boolean {
val colorStringLength = colorString.length
return colorStringLength == 7 || colorStringLength ==9
}
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
@RunWith(Parameterized::class)
class NormalizeColorParameterizedTest(
private val input: String?,
private val expected: String?
) {
@Test
fun shouldReturnExpectedColorCodeForColorString() {
val result = normalizeColor(input)
assertEquals(expected, result)
}
companion object {
@JvmStatic
@Parameters(name = "{index}: Input: {0} -> Output: {1}")
fun data(): List<Array<out String?>> = listOf(
arrayOf(null, null),
arrayOf("", null),
arrayOf("AABBCC", null),
arrayOf("#FFFFF", null),
arrayOf("#EEAABBCCD", null),
arrayOf("#AABBCC", "#AABBCC"),
arrayOf("#EEAABBCC", "#EEAABBCC"),
arrayOf("#AFF0097", "#FF0097")
)
}
private fun normalizeColor(colorString: String?): String? {
if (colorString.isNullOrEmpty()) {
return null
}
if (isInvalidColor(colorString)) {
return null
}
return if (isValidColorByLength(colorString)) {
colorString
} else {
val start = colorString.length.minus(6)
val normalizedColor = colorString.substring(start)
"#$normalizedColor"
}
}
private fun isInvalidColor(
colorString: String
): Boolean {
val minimumValidColorLengthWithHash = 7
val maximumValidColorLengthWithHash = 9
val colorStringLength = colorString.length
return !colorString.startsWith("#") ||
colorStringLength < minimumValidColorLengthWithHash ||
colorStringLength > maximumValidColorLengthWithHash
}
private fun isValidColorByLength(colorString: String): Boolean {
val colorStringLength = colorString.length
return colorStringLength == 7 || colorStringLength == 9
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment