Skip to content

Instantly share code, notes, and snippets.

@DNA

DNA/cpf.js

Created Aug 24, 2018
Embed
What would you like to do?
JS CPF validation
#! /usr/bin/env node
function validate_cpf(strCPF) {
if (new Set(strCPF).size == 1) return false
cpf = Array.from(strCPF).map(Number);
return [9, 10].every(pos => {
multiplier = pos + 1
vd = cpf.slice(0, pos).reduce((total, amount, index) => total + amount * (multiplier - index), 0);
vd = (vd * 10) % 11;
vd = (vd > 9) ? 0 : vd
if(vd == cpf[pos]) return true
})
}
let strCPF = "12345678909";
console.log(validate_cpf(strCPF));
@DNA

This comment has been minimized.

Copy link
Owner Author

@DNA DNA commented Aug 24, 2018

versão minimizada:

function v(s){if(new Set(s).size==1)return false;c=Array.from(s).map(Number);return[9,10].every(p=>{m=p+1;v=c.slice(0,p).reduce((t,a,i)=>t+a*(m-i),0);v=(v*10)%11;v=(v>9)?0:v;if(v==c[p])return true})}
@DNA

This comment has been minimized.

Copy link
Owner Author

@DNA DNA commented Aug 24, 2018

Versão ruby:

def v(s)c=s.chars.map(&:to_i);return if c.uniq.one?;[9,10].all?{|p|d=c[0,p].each_with_index.map{|a,i|a*(p-i+1)}.reduce(&:+)*10%11;(d>9?0:d)==c[p]}end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment