Created
November 20, 2024 23:36
-
-
Save wjuniorw/a1db0d8c056fb0e00395e16ad8068bfa to your computer and use it in GitHub Desktop.
validate CPF with functional programing paradigm in javascript
This file contains hidden or 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
| const clearCPF = cpf => cpf.replace(/\D/g, '') | |
| const validLength = cpf => cpf.length === 11 | |
| const redundant = cpf => cpf.split('').every(x => x === cpf[0]) | |
| const restOrZero = amount => (amount === 10 || amount === 11) ? 0 : amount | |
| const calculateDigits = cpf => { | |
| const numsStr = cpf.split('') | |
| const arrNums = Array.from(numsStr, n => +n) | |
| const nineDigits = arrNums.slice(0,9) | |
| const tenDigits = arrNums.slice(0,10) | |
| const weights = Array.from({ length: 9 }, (_, i) => 10 - i) | |
| const weights2 = Array.from({ length: 10 }, (_, i) => 11 - i) | |
| const amount1 = nineDigits.reduceRight((acc, digit, i) => acc + digit * weights[i], 0) | |
| const amount2 = tenDigits.reduceRight((acc, digit, i) => acc + digit * weights2[i], 0) | |
| const firstDigit = restOrZero(11 - (amount1 % 11)) | |
| const secondDigit = restOrZero(11 - (amount2 % 11)) | |
| return [firstDigit, secondDigit] | |
| } | |
| const getVerificationDigits = cpf => Array.from(cpf.split('').slice(9), n => +n) | |
| const isValidCPF = cpf => { | |
| const formatted = clearCPF(cpf) | |
| if (!validLength(formatted) || redundant(formatted)) { | |
| return false | |
| } | |
| const [first, second] = calculateDigits(formatted) | |
| const [firstDigit, secondDigit] = getVerificationDigits(formatted) | |
| return first === firstDigit && second === secondDigit | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment