Created
July 31, 2019 14:32
-
-
Save rsalomao2/efef214290d733230750abb4750cb787 to your computer and use it in GitHub Desktop.
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
fun String.isValidCPF(): Boolean { | |
if (this.isEmpty()) return false | |
val numbers = arrayListOf<Int>() | |
this.filter { it.isDigit() }.forEach { | |
numbers.add(it.toString().toInt()) | |
} | |
if (numbers.size != 11) return false | |
(0..9).forEach { n -> | |
val digits = arrayListOf<Int>() | |
(0..10).forEach { digits.add(n) } | |
if (numbers == digits) return false | |
} | |
val dv1 = ((0..8).sumBy { (it + 1) * numbers[it] }).rem(11).let { | |
if (it >= 10) 0 else it | |
} | |
val dv2 = ((0..8).sumBy { it * numbers[it] }.let { (it + (dv1 * 9)).rem(11) }).let { | |
if (it >= 10) 0 else it | |
} | |
return numbers[9] == dv1 && numbers[10] == dv2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment