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
- The
generateCreditCardNumber
function takes two parameters:prefix
andmaxLength
. - It concatenates random digits to the prefix until the desired length is reached.
- The check digit is calculated using Luhn’s algorithm to ensure the total sum (including the check digit) is divisible by 10.