CPF Generator
Generates a valid CPF with or without formatting.
How it works
First, we generate the first 9 digits
1const randomNumbers = () => Math.floor(Math.random() * 10);
2const cpf = Array.from({ length: 9 }, randomNumbers);
3
- This line creates an array of 9 random digits.
Array.from({ length: 9 })
generates an array with 9 undefined slots.- The
Math.random()
function generates a random number between 0 and 1, andMath.floor()
ensures the result is an integer between 0 and 9.
Then, we calculate the first and the second verification digit
1const calculateDigit = (base) => {
2const sum = base.reduce((acc, num, index) => acc + num * (base.length + 1 - index), 0);
3const digit = (sum * 10) % 11;
4return digit === 10 ? 0 : digit;
5
check out the complete source code: https://github.com/jvinezof-viaconsulting/js-tools/blob/main/src/generate-cpf/generate-cpf.ts