const REJECT_LIST = [ "00000000000" , "11111111111" , "22222222222" , "33333333333" , "44444444444" , "55555555555" , "66666666666" , "77777777777" , "88888888888" , "99999999999" , ] ; const STRICT_STRIP_REGEX = /[.-]/g ; const LOOSE_STRIP_REGEX = /[^\d]/g ; export param { string } numbers returns { number } export function verifierDigit ( numbers ) { const numberList = numbers . split ( "" ) . map ( ( number ) => parseInt ( number , 10 ) ) ; const modulus = numberList . length + 1 ; const multiplied = numberList . map ( ( number , index ) => number * ( modulus - index ) ) ; const mod = multiplied . reduce ( ( buffer , number ) => buffer + number ) % 11 ; return mod < 2 ? 0 : 11 - mod ; } export param { string } cpf returns { string } export function format ( cpf ) { return strip ( cpf ) . replace ( /^(\d{3})(\d{3})(\d{3})(\d{2})$/ , "$1.$2.$3-$4" ) ; } export param { string } cpf param { boolean } isStrict returns { string } export function strip ( cpf , isStrict = false ) { const regex = isStrict ? STRICT_STRIP_REGEX : LOOSE_STRIP_REGEX ; return ( cpf || "" ) . toString ( ) . replace ( regex , "" ) ; } export param { string } cpf param { boolean } isStrict returns { boolean } export function isValid ( cpf , isStrict = false ) { const stripped = strip ( cpf , isStrict ) ; if ( ! stripped ) { return false ; } if ( stripped . length !== 11 ) { return false ; } if ( REJECT_LIST . includes ( stripped ) ) { return false ; } let numbers = stripped . substr ( 0 , 9 ) ; numbers += verifierDigit ( numbers ) ; numbers += verifierDigit ( numbers ) ; return numbers . substr ( - 2 ) === stripped . substr ( - 2 ) ; } export param { boolean } useFormat returns { string } export function generate ( useFormat = false ) { let numbers = "" ; for ( let i = 0 ; i < 9 ; i += 1 ) { numbers += Math . floor ( Math . random ( ) * 9 ) ; } numbers += verifierDigit ( numbers ) ; numbers += verifierDigit ( numbers ) ; return useFormat ? format ( numbers ) : numbers ; }