Skip to content

Generating a Valid Credit Card Number Using Luhn's Algorithm

Published: at 01:17 AM

Here’s a JavaScript function to generate a valid credit card number using a specified prefix and maximum length:

function generateCreditCardNumber(prefix, maxLength) {
  let number = prefix;
  // this is string concatenation
  while (number.length < maxLength) {
    number += Math.floor(Math.random() * 10);
  }
  // We want the sum of generated digits and the check digit, to be divisible by 10
  // For the check digit, we'll substract the sum of generated digits from 10 and mod it by 10
  var checkDigit =
    (10 -
      number
        .split("")
        .reverse()
        .reduce((acc, c, i) => {
          // "==" replaced with ">" to catch odd places
          if ((i + 1) % 2 > 0) {
            c *= 2;
            if (c > 9) c -= 9;
          }
          return acc + Number(c);
        }, 0)) %
    10;
  return number + checkDigit;
}

var visaPrefix = "4539"; // Visa prefix
var maxLength = 16;
console.log(generateCreditCardNumber(visaPrefix, maxLength));

Explanation


Previous Post
Rotate and Spin
Next Post
Understanding the Luhn Algorithm