WebReference.com - Chapter 10 selections: Practical JavaScript for the Usable Web from glasshaus (4/5).
[previous] [next] |
Practical JavaScript for the Usable Web
First we check if isValid
is true (that is, if all other checks so far proved
satisfactory). Then, after our variable declarations, we have the main for loop that will go through
the credit card number a digit at a time starting with the last digit and moving to the first.
if (isValid)
{
var numberProduct;
var numberProductDigitIndex;
var checkSumTotal = 0;
for (digitCounter = cardNumberLength - 1;
digitCounter >= 0;
digitCounter--)
In this for loop we do a number of things. Firstly we add a digit's value to the running total,
checkSumTotal.
checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
Then we move to the digit that is one nearer the start of the card number string. We multiply this next digit by 2.
digitCounter--;
numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
We take the digits forming the results of the product calculation and in the inner for
loop we add these digits to the running total.
for (var productDigitCounter = 0;
productDigitCounter < numberProduct.length;
productDigitCounter++)
{
checkSumTotal +=
parseInt(numberProduct.charAt(productDigitCounter));
}
Our outer for
loop continues by moving to the next digit to the left, and
iterates until we reach the first digit in the credit card number string.
If we think back to the explanation of the Luhn formula, our approach is out of step in that we
are not doing step 1, then step 2, and so on, but instead are merging steps 1 Â 4 and processing
the number on a digit by digit basis, keeping a running total. It amounts to exactly the same
thing, but reduces the number of loops required. Let's summarize the steps in our outer and
inner for
loops:
Extract the character whose position is specified by
digitCounter
, from the string incardNumbersOnly
.Add this number to our running total, which is kept in variable
checkSumTotal
.Decrement the character counter,
digitCounter
. This now refers to the next digit to the left in our stringcardNumbersOnly
.Extract the next digit, convert it to a number, and then double it. This is all done on one line and this product is stored in variable
numberProduct.
Convert the product calculated in step 4 to a string.
Loop through each digit in the product string, convert it to an integer, and add to the running total. This is our inner
for
loop. For example, if the character extracted in step 4 was 8, its product would be 16, and so we'd add 1 and then 6 to our running total.Decrement the
digitCounter
and move to step 1.
[previous] [next] |
Created: April 15, 2002
Revised: April 19, 2002
URL: https://webreference.com/programming/javascript/practical/chap10/4.html