Skip to content

Instantly share code, notes, and snippets.

@paulofellix
Forked from suissa/cpf.validate.final.js
Last active October 8, 2020 21:28
Show Gist options
  • Save paulofellix/a4e56a04ba6f42977261af190ae0eb60 to your computer and use it in GitHub Desktop.
Save paulofellix/a4e56a04ba6f42977261af190ae0eb60 to your computer and use it in GitHub Desktop.
[JS Util Functions] #javascript
const mod11 = ( num ) => num % 11
const NOT = ( x ) => !x
const isEqual = ( a ) => ( b ) => b === a
const mergeDigits = ( num1, num2 ) => `${num1}${num2}`
const getTwoLastDigits = ( cpf ) => `${cpf[ 9 ]}${cpf[ 10 ]}`
const getCpfNumeral = ( cpf ) => cpf.substr( 0, 9 ).split( '' )
const isRepeatingChars = ( str ) =>
str.split( ‘’ ).every( ( elem ) => elem === str[ 0 ] )
const toSumOfProducts = ( multiplier ) => ( result, num, i ) =>
result + ( num * multiplier-- )
const getSumOfProducts = ( list, multiplier ) =>
list.reduce( toSumOfProducts( multiplier ), 0 )
const getValidationDigit = ( multiplier ) => ( cpf ) =>
getDigit( mod11( getSumOfProducts( cpf, multiplier ) ) )
const getDigit = ( num ) =>
( num > 1 )
? 11 - num
: 0
const isRepeatingNumbersCpf = isRepeatingChars
const isValidCPF = ( cpf ) => {
const CPF = getCpfNumeral( cpf )
const firstDigit = getValidationDigit( 10 )( CPF )
const secondDigit = getValidationDigit( 11 )( CPF.concat( firstDigit ) )
return isEqual( getTwoLastDigits( cpf ) )
( mergeDigits( firstDigit, secondDigit ) )
}
const validate = ( CPF ) => NOT( isRepeatingNumbersCpf( CPF ) ) && isValidCPF( CPF )
const CPFS = [
'04998264931', '03506838326','04864713901',
'03506838321', '22222222222', '00000000000'
]
CPFS.forEach( ( cpf ) => console.log( `${cpf}: ${validate( cpf )}` ) )
function CreateUUID() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
function CreateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function buildFormData(formData, data, parentKey) {
if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
Object.keys(data).forEach(key => {
buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
});
} else {
const value = data == null ? '' : data;
formData.append(parentKey, value);
}
}
function jsonToFormData(data) {
const formData = new FormData();
buildFormData(formData, data);
return formData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment