Skip to content

Instantly share code, notes, and snippets.

@seventhmoon
Last active April 12, 2021 00:53
Show Gist options
  • Save seventhmoon/89127c7d10fd63daff4fdacccaa01ec4 to your computer and use it in GitHub Desktop.
Save seventhmoon/89127c7d10fd63daff4fdacccaa01ec4 to your computer and use it in GitHub Desktop.
HkidValidator
import java.lang.IllegalArgumentException
class HkidValidator {
private val acceptedChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ "
private val hkidRegex = Regex("[A-Z]{1,2}\\d{6}")
@ExperimentalStdlibApi
fun calcCheckDigit(input: String): Char {
return if (input.matches(hkidRegex)) {
val id = if (input.length == 7) " $input" else input
val sum = id.mapIndexed { index, c ->
(9 - index) * acceptedChars.indexOf(c)
}.sum()
val checksum = (11 - (sum % 11) % 11)
checksum.digitToChar(16)
} else throw IllegalArgumentException()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment