Skip to content

Instantly share code, notes, and snippets.

@DNA
Created August 24, 2018 17:31
Show Gist options
  • Save DNA/e130548e640637721fba69cf46f68311 to your computer and use it in GitHub Desktop.
Save DNA/e130548e640637721fba69cf46f68311 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link
Author

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