Last active
July 6, 2020 04:19
-
-
Save guibarbosadev/2332bb629f792285936379c5f1f39fda to your computer and use it in GitHub Desktop.
Gerador de CPF
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
function validatorDigit(CPF) { | |
const CPFCopy = [...CPF]; | |
const initialSumValue = 0; | |
const sum = CPFCopy.reverse().reduce((previousValue, currentValue, index) => { | |
const multiplicator = index + 2; | |
const currentSum = previousValue + currentValue * multiplicator; | |
return currentSum; | |
}, initialSumValue); | |
const digit = (sum * 10) % 11; | |
return digit < 10 ? digit : 0; | |
} | |
function generateRandomNumbers(numbersToGenerate = 1) { | |
return Array.from({ length: numbersToGenerate }, () => { | |
return parseInt(Math.random() * 10); | |
}); | |
} | |
function maskCPF(CPF = '') { | |
const mask = /(\d{3})(\d{3})(\d{3})(\d{2})/; | |
const withMask = CPF.replace(mask, '$1.$2.$3-$4'); | |
return withMask; | |
} | |
function generateCPF(withMask = false) { | |
let CPF = generateRandomNumbers(9); | |
CPF.push(validatorDigit(CPF)); | |
CPF.push(validatorDigit(CPF)); | |
CPF = CPF.join(''); | |
if (withMask === true) { | |
CPF = maskCPF(CPF); | |
} | |
return CPF; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment