Luhn

in #ita2 months ago

//
// This is only a SKELETON file for the 'Luhn' exercise. It's been provided as a
// convenience to get you started writing code faster.
//

export const valid = (candidate) => {
let totalSum = 0;
candidate = candidate.replace(/\s/g, "");
if(candidate.length <=1) return false;
for(let n = candidate.length-1; n>=0; n--){
if(isNaN(candidate[n])) return false;
if(candidate.length % 2 == 0){
if(n % 2 == 0){
let numCandidate = parseInt(candidate[n], 10);
numCandidate *= 2;
if(numCandidate >9) numCandidate -=9;
totalSum += numCandidate;
}
else{
let numCandidatetwo = parseInt(candidate[n], 10);
totalSum += numCandidatetwo;
}
}
else{
if(n % 2 != 0){
let numCandidate = parseInt(candidate[n], 10);
numCandidate *= 2;
if(numCandidate >9) numCandidate -=9;
totalSum += numCandidate;
}
else{
let numCandidatetwo = parseInt(candidate[n], 10);
totalSum += numCandidatetwo;
}
}
}
return totalSum % 10 == 0;
};