Sunday, July 15, 2018

[JavaScript][Exercise] check membershipID digit.

Your company assigns each customer a membership ID, and you are implementing a check digit for those IDs.

The check digit should be calculated by adding up all digits in each membership ID. If the result of the sum is a number with more than a single digit, another iteration is required, and the digits of the result also should be added together. This process should repeat until a single-digit number is calculated.

For example, for the membership ID "55555" the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result, 7, would be the check digit.

Reference answer

To get 100% marks, you need to fit 4 requirements:
  1. Fit example case (55555)
  2. Single iteration required
  3. Two iterations required
  4. Multiple iterations required
 We need recursive function:
function createCheckDigit(membershipId) {
  var sum = 0;
  for(var i=0;i<membershipId.toString().length;i++){
    sum += parseInt(membershipId.toString()[i]);
  }
  if(sum.toString().length>1){
    sum = createCheckDigit(sum);
  }
  return sum;
}

No comments :

Post a Comment