I'm learning Javascript on Codecademy and have gotten stumped by a problem. I believe my issue is with the scope of my iterator tracker but not too sure.
Here are the directions given to me: "Create a function, validateCred() that has a parameter of an array. The purpose of validateCred() is to return true when an array contains digits of a valid credit card number and false when it is invalid. This function should NOT mutate the values of the original array.
To find out if a credit card number is valid or not, use the Luhn algorithm. Generally speaking, an algorithm is a series of steps that solve a problem — the Luhn algorithm is a series of mathematical calculations used to validate certain identification numbers, e.g. credit card numbers. The calculations in the Luhn algorithm can be broken down as the following steps:
Starting from the farthest digit to the right, AKA the check digit, iterate to the left. As you iterate to the left, every other digit is doubled (the check digit is not doubled). If the number is greater than 9 after doubling, subtract 9 from its value. Sum up all the digits in the credit card number.
If the sum modulo 10 is 0 (if the sum divided by 10 has a remainder of 0) then the number is valid, otherwise, it’s invalid. Here’s a visual that outlines the steps. Check your function using both the provided valid and invalid numbers."
Here's an array that should be passed into this function and return true:
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
Here's an array that should return false:
const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];
Lastly, here's my code for trying to solve this:
function validateCred(arr) {
//Keeps track for the sum modulo later on
let totalSum = 0;
//Iterates to the left
for (let i = arr.length; i > 0; i--) {
//Keeps track of place to later double every other digit
let iterater = 1;
//Checks for every other digit and doubles it
if (iterater % 2 === 0) {
//Doubles it
let doubledAmnt = arr[i] * 2;
//Checks if doubled amount is greater than 9
if (doubledAmnt > 9) {
totalSum += (doubledAmnt - 9);
//Adds the doubled amount if not over 9
} else {
totalSum += doubledAmnt;
}
//Adds the digit if it does not need to be doubled
} else {
totalSum += arr[i];
};
//Adds to place tracker (I think my problem is here?)
iterater++
};
//Checks if the total sum is divisible by 10 to return true or false
if (totalSum % 10 === 0) {
return true;
} else {
return false;
}
}