Last active
April 12, 2021 00:53
-
-
Save seventhmoon/89127c7d10fd63daff4fdacccaa01ec4 to your computer and use it in GitHub Desktop.
HkidValidator
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
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