Skip to content

Instantly share code, notes, and snippets.

@matheustp
Last active October 31, 2017 18:46
Show Gist options
  • Save matheustp/842ec3269d8b5c7649075b0126c82fc8 to your computer and use it in GitHub Desktop.
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
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
@matheustp
Copy link
Author

Técnicas utilizadas:

  • Code style do curso;
  • Arrow function;
  • Ifs ternários;
  • Closure;
  • Agrupamento de testes lógicos;
  • Destructuring assignment;
  • Função de validação;
  • Retorno de função como Array;
  • Uso de every para comparar 2 arrays;

@suissa
Copy link

suissa commented Jul 15, 2017

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