Skip to content

Instantly share code, notes, and snippets.

@gabfssilva
Last active April 14, 2023 13:54
Show Gist options
  • Save gabfssilva/b209c48dd4a921689ec499021556f071 to your computer and use it in GitHub Desktop.
Save gabfssilva/b209c48dd4a921689ec499021556f071 to your computer and use it in GitHub Desktop.
Validator de CPF em Kotlin utilizando FP
val knownInvalidCpfs =
(0..9)
.map { i -> (1..11).map { i } }
.map { it.joinToString("") }
fun isValid(document: String): Boolean {
if (document in knownInvalidCpfs) return false
val numbers = document.mapNotNull { it.digitToIntOrNull() }
fun check(digit: Int) =
numbers
.zip((9 + digit) downTo 2)
.sumOf { (f, s) -> f * s }
.let { it * 10 % 11 }
.let { if (it == 10) 0 else it } == numbers[8 + digit]
return check(1) && check(2)
}
fun main() {
isValid("32612124624").also(::println) //true
isValid("11111111111").also(::println) //false
isValid("84729378292").also(::println) //false
isValid("38736526681").also(::println) //true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment