Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refatoração da função format #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions src/format.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
const mask = {
cpf(val) {
return val
.replace(/(\d{11})\d/, '$1')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1-$2');
},
};


const onlyDigits = val => {
return val.replace(/\D/g, '');
};

/**
* Format a CPF number.
*
* @param {string} cpf Unformatted CPF number.
* @returns {string} Formatted CPF number.
*/
module.exports = (cpfNumber) => {
if (typeof cpfNumber !== 'string') {
throw new Error('Invalid CPF number')
}

const unformattedCpf = cpfNumber.replace(/\D/g, '')

if (unformattedCpf.length !== 11) {
throw new Error('Invalid CPF number')
}

const regex = /^(\d{3})(\d{3})(\d{3})(\d{2})$/
const mask = '$1.$2.$3-$4'

return unformattedCpf.replace(regex, mask)
const digits = onlyDigits(cpfNumber);
return mask.cpf(digits);
}