Reputation: 99
I'm doing a credit card validation task and when I check given numbers who are 16-digit long everything seemed to work fine, but that was not the case when I entered 15-digit number. Then while debugging with console.logs I noticed that my 'i' values are not what I expect them to be and it seems that is the reason why it doesn't work properly, but I can't fix it. Here is my code, sorry for a lot of console.logs...
const validateCred = (array) => {
let sum = 0;
let newArray = array.slice()
let popped = newArray.pop()
console.log(array)
console.log(newArray, popped)
let reversedArray = newArray.reverse();
console.log(reversedArray, popped)
for (let i = 0; i < reversedArray.length; i++) {
if (i % 2 === 0) {
console.log('value', i, array[i])
array[i] = array[i] * 2 > 9 ? array[i] * 2 - 9 : array[i] * 2;
console.log('new', array[i])
} else {
array[i] = array[i]
console.log('value', i, array[i])
}
sum += array[i]
console.log(sum)
}
sum += popped
console.log(sum)
sum % 10 === 0 ? console.log(true) : console.log(false)
}
const valid3 = [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6];
validateCred(valid3)
So, after I reverse the array, I expected that 'i' of 0 would be 3 and 'i' of 1 to be 2, but as you can see from console.logs 'i' of 2 is 7 as if I didn't reverse the array. What am I doing wrong here?
Upvotes: 1
Views: 63
Reputation: 6336
You declared for (let i = 0; i < reversedArray.length; i++) {
but you are running on array[i]
. You need to use reversedArray[i]
.
Upvotes: 2