Credit Card Checker

Phew. This problem doesn’t seem complicated, but for some reason I get it wrong. I did two iterations of the problem. In the first one I did a couple of functions in order to do the validation of the numbers.
Now I tried doing it in one function (I will leave the task of not mutating the initial array for the end - ignore for now).
I have the following function:

const validateCred1 = arr => {
  let lastDigit = arr[arr.length - 1];
  console.log(lastDigit);
  arr.pop();
  arr.reverse();
  console.log(arr);
  for (let i = 0; i < arr.length; i++) {
    if (i % 2 > 0) {
      arr[i] * 2;
      if (arr[i] > 9) {
        arr[i] -= 9;
      }
    }
    if (i % 2 === 0) {
      arr[i];
    }
    doubleNumberSum += arr[i];
  }
  return doubleNumberSum + lastDigit;
};

console.log(validateCred1(valid1));

I am checking using this array:

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];

If I do the result % 10 I should get 0, but for some reason I don’t. At this point I think I too stuck to think what I have done wrong.
Can anyone help me with that?

You have this line…

if (i % 2 > 0) {
      arr[i] * 2; // <-- this one

but the question is, is it affecting anything?

1 Like

From what I can see it does.
For some reason the I get a wrong number.

Regards,

Tsvetan

This is the code:

if (i % 2 > 0) {
      arr[i];
      console.log(arr[i]);

I’ll be a bit more explicit:

if (i % 2 > 0) {
      arr[i] * 2; // <-- this one

this code is effectively not doing doing (because all is doing is calculating twice arr[i] but not storing or changing anything.

Hope this helps!

1 Like

My code that works is:

const validateCred = arr => {
  let num = 0;
  let total = 0;
  if (arr.length % 2 !== 0) {
    arr.unshift(0);
  }
  for(let i = arr.length -1; i > -1; i--) {
    number = arr[i];
    if (i % 2 === 0) {
      number *= 2;
      if (number > 9) {
        number -= 9;
      }
      total += number;
  }
  
  return total % 10 === 0;
}

Works? Runs without error maybe, but you are removing the first digit from numbers that have an odd length. Not only are you mutating the original array, you aren’t validating the original number.

Yeah, this is it. I made the changes, actually rewrote the entire question in order to not mutate the initial array. This helps.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.