Last active
August 10, 2021 22:10
-
-
Save adriandelgado/6049e01e4974257ab2704a86a0d5d6b5 to your computer and use it in GitHub Desktop.
Algoritmo de validación de cédulas ecuatorianas en Rust
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
const NUM_PROV_ECUADOR: i8 = 24; | |
pub fn es_cedula_ecuatoriana<T: AsRef<str>>(cedula: T) -> bool { | |
let cedula = cedula.as_ref(); | |
if cedula.len() != 10 { | |
return false; | |
} | |
// Se genera un vector de dígitos i8, retorna temprano si no todos son dígitos | |
let digitos = match cedula | |
.chars() | |
.try_fold(Vec::with_capacity(10), |mut acc, c| { | |
let digito = c.to_digit(10)? as i8; | |
acc.push(digito); | |
Some(acc) | |
}) { | |
Some(digitos) => digitos, | |
None => return false, | |
}; | |
// primeros dos dígitos: [AB] = 10*A + B | |
let provincia = 10 * digitos[0] + digitos[1]; | |
// extranjeros == 30 | |
if (provincia != 30 && provincia > NUM_PROV_ECUADOR) || provincia == 0 { | |
return false; | |
} | |
// algoritmo de luhn | |
let suma = digitos | |
.iter() | |
.zip([2, 1, 2, 1, 2, 1, 2, 1, 2, 1].iter()) | |
.map(|(digito, coeficiente)| (digito * coeficiente - 1) % 9 + 1) | |
.sum::<i8>() | |
% 10; | |
suma == 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment