Reputation: 2041
I have this number 55555
If we add this single number then the result will be = 25 and then if we add 2 + 5 then the result will be 7.
I want to make it but can't get the result:
What I have done so far:
function createCheckDigit(membershipId) {
// Write the code that goes here.
string = membershipId.split('');
let sum = 0;
for (var i = 0; i < string.length; i++) {
sum += parseInt(string[i],10);
}
console.log(sum.split(''));
}
console.log(createCheckDigit("55555"));
Upvotes: 0
Views: 998
Reputation: 61
function makesum(value)
{
return value.toString().split('').reduce((a,b) => a/1+b/1);
}
function actualFunction(newvalue)
{
if(newvalue.toString().split('').length < 2)
{
return makesum(newvalue);
}
else
{
return makesum(makesum(newvalue));
}
}
console.log(actualFunction(55555))
console.log(actualFunction(1111111111))
console.log(actualFunction(99))
Upvotes: 0
Reputation: 371168
Make the function recursive - after the loop, if the sum is 10 or more, call it again:
function createCheckDigit(membershipId) {
// Write the code that goes here.
string = membershipId.split('');
let sum = 0;
for (var i = 0; i < string.length; i++) {
sum += parseInt(string[i],10);
}
return sum >= 10 ? createCheckDigit(String(sum)) : sum;
}
console.log(createCheckDigit("55555"));
Or, more concisely:
function createCheckDigit(num) {
const nextNum = num.split('').reduce((a, b) => a + Number(b), 0);
return nextNum >= 10 ? createCheckDigit(String(nextNum)) : nextNum;
}
console.log(createCheckDigit("55555"));
Upvotes: 4