Mod 10 Check Digit


The Code

function getCheckDigit(num) {
  let sum = 0;

  for (let i = 0; i < num.length; i++) {
    let digit = parseInt(num[num.length - 1 - i], 10); // Loop through each digit from right to left

    if (i % 2 === 0) { // Double every second digit starting from first digit
      digit *= 2;
      if (digit > 9) { // Add the digits of numbers >1 digit, i.e., 2x7=14, 1+4=5 or 14-9=5
        digit -= 9;
      }
    }

    sum += digit; // Sum all the numbers
  }

  return (10 - (sum % 10)) % 10;
}