Last active
October 31, 2017 18:46
-
-
Save matheustp/842ec3269d8b5c7649075b0126c82fc8 to your computer and use it in GitHub Desktop.
Código de validação do titulo de eleitor extraído do site do TSE
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 getDataFromInscricao = ( inscricao ) => [ | |
inscricao.substr( inscricao.length - 2, 2 ), | |
inscricao.substr( inscricao.length - 4, 2 ), | |
inscricao.substr( 0, inscricao.length - 2 ) | |
] | |
const calcSum1 = ( titulo ) => | |
titulo.substr( 0, 8 ).split( '' ).reduce( ( total, val, i ) => total += val * ( 9 - i ), 0 ) | |
const fixDigit = ( exce ) => ( dig ) => | |
( dig < 10 ) | |
? dig | |
: getLastDigit( dig, exce ) | |
const getLastDigit = ( dig, exce ) => ( dig === 11 && exce ) ? 1 : 0 | |
const calcDig1 = ( titulo ) => | |
11 - ( calcSum1( titulo ) % 11 ) | |
const calcDig2 = ( titulo, dig1 ) => | |
11 - ( ( (titulo[ 8 ] ) * 4 + ( titulo[ 9 ] ) * 3 + dig1 * 2 ) % 11 ) | |
const calcDigits = ( titulo, exce ) => [ | |
dig1 = fixDigit( exce )( calcDig1( titulo ) ), | |
dig2 = fixDigit( exce )( calcDig2( titulo, dig1 ) ) | |
] | |
const isAnException = ( estado ) => | |
[ '01', '02' ].find( ( val ) => val === estado ) | |
const validarTitulo = ( inscricao ) => { | |
const [ digitos, estado, titulo ] = getDataFromInscricao( inscricao ) | |
return calcDigits( titulo, isAnException( estado ) ).every( ( val, i ) => val === +digitos[ i ] ) | |
} | |
console.log( validarTitulo( '051823250108' ) ) // true | |
console.log( validarTitulo( '870642332720' ) ) // true |
PERFEITOOOO!!!!
Quero ver alguém conseguir fazer melhor.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Técnicas utilizadas: