Credit Card Checker Challenge Project (JavaScript)

Hello, after putting in a day and a half of effort, I completed the challenge with some assistance. I’m balancing work and study commitments, and I’m doing my best to dedicate time to learning.

Git hub Repositiry

View my code and be the judge:

Found this one quite tough, never would of thought of completing the validateCred function in the way provided by the solution - feels like I still have a lot to learn. Wish there was a video to go along with this to try and understand the steps it took to reach the given solution too.

Gave up on trying to find a way to convert invalid numbers to valid ones, my brain just couldn’t work it out. Has anyone got a solution or tried to do it?

Here’s my solution to the challenge so far: https://github.com/MagonBorn/CreditCardChecker/blob/main/app.js

Matt

You have a minor typo at the decremental operator part within the first loop (should be i--)

Variables defined within an if or else block are scoped only to that block and cannot be accessed outside of it. In your case, uniqueFirstNumbers is defined either within the if block or the else block, and you’re trying to access it outside of those blocks, which results in a ReferenceError. To fix this, you need to declare uniqueFirstNumbers outside of the if-else block, so it’s accessible in the broader scope of the function.

Hi all here is my version, I see now I overcomplicated a few lines but I guess that is the part of the process :slight_smile:

I have a hard time learning javascript. I put the effort and understand how it articulates and the logic behind it but the more I do those exercises, the more I ask myself if this way of learning is obsolete.

I completed the exercise in 5 minutes with chat GPT. In real life, if I need to solve a problem, I would also turn to a GPT. So what’s the point ?

I’m 45. I studied the old-way, pre-internet, with books. Relying on AI to solve problems seemed wrong at first but then I remember the time when I had to remember telephone numbers and how I stopped learning them the moment I had a smartphone. Well, it feels like I don’t need to rely on MY intelligence to solve problems anymore.

Maybe there’s a way for codecademy to recycle it’s current material and focus on how to articulate questions more than finding answers.

Can’t wait to finish this chapter and move on to building website again.

Ok, so I think my code works well, but after looking at some other solutions, I think I did it way longer than I should’ve haha. Here it is:

const validCards = [];
const invalidCards = [];

const validateCred = arr => {
    let rawArr = arr.join('');
    const lastDigit = arr[arr.length - 1];
    const reversedNums = [];
    const oddDigits = [];
    const restOfDigits = [];
    const processedDigits = [];
        for (let i = arr.length - 2; i >= 0; i--) { // Rellena el array 'reversedNums' con los numeros invertidos del array (menos el ultimo digito)
            reversedNums.push(arr[i]);
        }
        for (let i = 0; i < reversedNums.length; i = i + 2) { // Rellena el array 'oddDigits' con "numero por medio"
            oddDigits.push(reversedNums[i]);
        };
        for (let i = 1; i < reversedNums.length; i = i + 2) { // Rellene al array 'restOfNumbers' con el resto de los numeros.
            restOfDigits.push(reversedNums[i]);
        }
        for (let i = 0; i < oddDigits.length; i++) { // Rellena el array 'processedDigits' con el resultado de la multiplicacion de los digitos *2 y -9 en el caso de los que sean mayores a 9
          let multiply = (oddDigits[i] * 2);
          if (multiply > 9){
            multiply = multiply - 9;
          }
          processedDigits.push(multiply);
        };
        
        const finalNumber = restOfDigits.concat(processedDigits);
        const result = finalNumber.reduce((a,b) => a+b);
        const addDropped = result + lastDigit;
        const isValid = numToCheck => {
            if (addDropped % 10 === 0) {
                validCards.push(`${rawArr}`);
                return 'Valid Credit Card'; 
            } else {
                invalidCards.push(`${rawArr}`)
                return 'Invalid Credit Card';
            };
        }

        return isValid(addDropped)
    };

    const mapCC = batch.map(validateCred);

const idInvalidCardCompanies = arr => {
    const invalidCompanies = [];
    arr.forEach(ccnumber => {
       
        if (ccnumber[0] === '3' && invalidCompanies.indexOf('Amex(American Express)') === -1) {
        invalidCompanies.push('Amex(American Express)')
        } else if (ccnumber[0] === '4' && invalidCompanies.indexOf('Visa') === -1) {
        invalidCompanies.push('Visa')
        } else if (ccnumber[0] === '5' && invalidCompanies.indexOf('Mastercard') === -1) {
        invalidCompanies.push('Mastercard')
        } else if (ccnumber[0] === '6' && invalidCompanies.indexOf('Discover') === -1) {
         invalidCompanies.push('Discover')
        } else {
        return 'Company not Found'
        }
    } );
    return invalidCompanies;
}
console.log(idInvalidCardCompanies(invalidCards));
console.log(`Valid Card Numbers: ${validCards}`);
console.log(`Invalid Card Numbers : ${invalidCards}`);

Jims Credit Card Checker solution

Hi, Just completed this,

I found it difficult but rewarding to see it working at the end.

Something I also try to do when I get these to work is to attempt to condense the lines of code, I initially had some helper functions in but was able to shorten the code and eliminate the need for these. Yes it took longer to complete but I was happier with the final result as I felt it was less muddled and easier to follow.

I did wonder if these more difficult projects where meant to follow on from the pairing section, giving 2 people something with more teeth to work on. I haven’t managed to pair with anyone yet on a project so if you are in the same boat then maybe we can help each other out, so feel free to contact me.

best of luck with the rest of the course

Jim

I was pretty excited to finally complete this - this was definitely the toughest project I’ve come across so far as a new coder.

My code

After viewing the provided solution, I feel a little deflated because of how different it is and how much more efficient the code is. For example it didn’t occur to me that returning the result of the first part mod 10 could be done in one line by simply returning the result. I did an if/else to return true/false :sweat:

  if (sum % 10 == 0){
    return true;
  } else {
    return false;
  }

I’m curious to know how long it took more seasoned coders to feel like their code was becoming more efficient or elegant.

Edit: It actually seems like my last function doesn’t work with singular arrays, only the batch ones! Would love any advice on what could be wrong there!

1 Like

I have the same question about time and my code also seems inefficient :smiling_face:! I am going down the line of being confident with what I am currently creating and then work on making it more concise :crossed_fingers:

My code

Hi! What about my code?) If you check it, I will be happy.

function validateCred(card) {
let digits = card.slice();

for (let i = digits.length - 2; i >= 0; i -= 2) {
digits[i] *= 2;
if (digits[i] > 9) {
digits[i] -= 9;
}
}
const sum = digits.reduce((acc, curr) => acc + curr, 0);
return sum % 10 === 0;
}

function findInvalidCards(cardArray) {
const invalidCards = ;
for (let card of cardArray) {
if (!validateCred(card)) {
invalidCards.push(card);
}
}
return invalidCards;
}

function idInvalidCardCompanies(invalidCards) {
const uniqueCompanies = {};
for (let card of invalidCards) {
let firstDigit = card[0];

switch (firstDigit) {
  case 3:
   if (!uniqueCompanies.includes('Amex')) {
    uniqueCompanies.push('Amex');
   }
   break;
  case 4:
   if (!uniqueCompanies.includes('Visa')) {
    uniqueCompanies.push('Visa');
   }
   break;
  case 5:
   if (!uniqueCompanies.includes('Mastercard')) {
    uniqueCompanies.push('Mastercard');
   }
   break;
  case 6:
   if (!uniqueCompanies.includes('Discover')) {
    uniqueCompanies.push('Discover');
   }
   break;
   default:
    console.log("Company not found"); 

}
}

return uniqueCompanies;
}

Hello All,

This is still very much a work in progress. I am still trying to make sure I understand what I actually coded. Any feedback would be greatly appreciated.

Codepen has been updated. It should match the below Gist

// All valid credit card numbers const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; const valid2 = [5, 5, 3, 5, 7, 6, 6, 7, 6, 8, 7, 5, 1, 4, 3, 9]; const valid3 = [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6]; const valid4 = [6, 0, 1, 1, 1, 4, 4, 3, 4, 0, 6, 8, 2, 9, 0, 5]; const valid5 = [4, 5, 3, 9, 4, 0, 4, 9, 6, 7, 8, 6, 9, 6, 6, 6]; // All invalid credit card numbers const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5]; const invalid2 = [5, 7, 9, 5, 5, 9, 3, 3, 9, 2, 1, 3, 4, 6, 4, 3]; const invalid3 = [3, 7, 5, 7, 9, 6, 0, 8, 4, 4, 5, 9, 9, 1, 4]; const invalid4 = [6, 0, 1, 1, 1, 2, 7, 9, 6, 1, 7, 7, 7, 9, 3, 5]; const invalid5 = [5, 3, 8, 2, 0, 1, 9, 7, 7, 2, 8, 8, 3, 8, 5, 4]; // Can be either valid or invalid const mystery1 = [3, 4, 4, 8, 0, 1, 9, 6, 8, 3, 0, 5, 4, 1, 4]; const mystery2 = [5, 4, 6, 6, 1, 0, 0, 8, 6, 1, 6, 2, 0, 2, 3, 9]; const mystery3 = [6, 0, 1, 1, 3, 7, 7, 0, 2, 0, 9, 6, 2, 6, 5, 6, 2, 0, 3]; const mystery4 = [4, 9, 2, 9, 8, 7, 7, 1, 6, 9, 2, 1, 7, 0, 9, 3]; const mystery5 = [4, 9, 1, 3, 5, 4, 0, 4, 6, 3, 0, 7, 2, 5, 2, 3]; // An array of all the arrays above const batch = [ valid1, valid2, valid3, valid4, valid5, invalid1, invalid2, invalid3, invalid4, invalid5, mystery1, mystery2, mystery3, mystery4, mystery5, ]; // Add your functions below: let isValid = false; function validateCred(arr) { let copyArr = Array.isArray(arr) ? arr.slice().reverse() : arr.toString().split("").reverse().map(Number); // Check if arr is an array, if not convert it to an array let sum = 0; let isEven = false; for (let i = 0; i < copyArr.length; i++) { let digit = parseInt(copyArr[i]); if (isEven) { digit *= 2; if (digit > 9) { digit -= 9; } } sum += digit; isEven = !isEven; } isValid = sum % 10 === 0; console.log( `The card number: ${arr} has been validated. Is it valid? Result: ${isValid}` ); return arr; } function findInvalidCards(batch) { let invalidCards = []; for (let i = 0; i < batch.length; i++) { validateCred(batch[i]); // Run validateCred() to update isValid if (!isValid) { invalidCards.push(batch[i]); } } console.log("The below card numbers are not valid:"); return invalidCards; } function idInvalidCardCompanies(invalidNumbers) { let companies = []; // Convert single array or string to an array of arrays if (!Array.isArray(invalidNumbers[0])) { invalidNumbers = [invalidNumbers]; } else if (typeof invalidNumbers === "string") { invalidNumbers = [invalidNumbers.split("").map(Number)]; } for (let i = 0; i < invalidNumbers.length; i++) { let firstDigit = invalidNumbers[i][0]; switch (firstDigit) { case 3: if (!companies.includes("Amex")) { companies.push("Amex"); console.log(invalidNumbers[i][0]); } break; case 4: if (!companies.includes("Visa")) { companies.push("Visa"); console.log(invalidNumbers[i][0]); } break; case 5: if (!companies.includes("Mastercard")) { companies.push("Mastercard"); console.log(invalidNumbers[i][0]); } break; case 6: if (!companies.includes("Discover")) { companies.push("Discover"); console.log(invalidNumbers[i][0]); } break; default: console.log(invalidNumbers[i][0]); console.log("Company not found"); } } return companies; } console.log(validateCred(invalid1)); console.log(findInvalidCards(batch)); // console.log(idInvalidCardCompanies(findInvalidCards(batch))); // console.log(idInvalidCardCompanies(validateCred(invalid2))); // console.log(idInvalidCardCompanies(invalid2)); // console.log(idInvalidCardCompanies(validateCred(invalid1))); // console.log(validateCred(valid1)); // console.log(validateCred(invalid1));

Hey @jwl298,

Take a look at the codepen I posted Credit Card Checker Challenge Project (JavaScript) - #1461 by tiercen82

I think I am doing what you are trying to do. I found that if you pass it a single array you have to turn it into a nested array first before processing it. I also tried to make it so that idInvalidCardCompanies() could handle the return from validateCred(). So my validateCred() returns the checked array. I also modified it to accept a number or a string in addition to an array.

I created a workspace so I can continue to refine. I would love your feedback.

https://www.codecademy.com/workspaces/65d7c065c1a4b16c3b60327e

I am not able to edit the existing post anymore. So here is the new codpen

// All valid credit card numbers const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; const valid2 = [5, 5, 3, 5, 7, 6, 6, 7, 6, 8, 7, 5, 1, 4, 3, 9]; const valid3 = [3, 7, 1, 6, 1, 2, 0, 1, 9, 9, 8, 5, 2, 3, 6]; const valid4 = [6, 0, 1, 1, 1, 4, 4, 3, 4, 0, 6, 8, 2, 9, 0, 5]; const valid5 = [4, 5, 3, 9, 4, 0, 4, 9, 6, 7, 8, 6, 9, 6, 6, 6]; // All invalid credit card numbers const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5]; const invalid2 = [5, 7, 9, 5, 5, 9, 3, 3, 9, 2, 1, 3, 4, 6, 4, 3]; const invalid3 = [3, 7, 5, 7, 9, 6, 0, 8, 4, 4, 5, 9, 9, 1, 4]; const invalid4 = [6, 0, 1, 1, 1, 2, 7, 9, 6, 1, 7, 7, 7, 9, 3, 5]; const invalid5 = [5, 3, 8, 2, 0, 1, 9, 7, 7, 2, 8, 8, 3, 8, 5, 4]; // Can be either valid or invalid const mystery1 = [3, 4, 4, 8, 0, 1, 9, 6, 8, 3, 0, 5, 4, 1, 4]; const mystery2 = [5, 4, 6, 6, 1, 0, 0, 8, 6, 1, 6, 2, 0, 2, 3, 9]; const mystery3 = [6, 0, 1, 1, 3, 7, 7, 0, 2, 0, 9, 6, 2, 6, 5, 6, 2, 0, 3]; const mystery4 = [4, 9, 2, 9, 8, 7, 7, 1, 6, 9, 2, 1, 7, 0, 9, 3]; const mystery5 = [4, 9, 1, 3, 5, 4, 0, 4, 6, 3, 0, 7, 2, 5, 2, 3]; // An array of all the arrays above const batch = [ valid1, valid2, valid3, valid4, valid5, invalid1, invalid2, invalid3, invalid4, invalid5, mystery1, mystery2, mystery3, mystery4, mystery5, ]; // Add your functions below: let isValid = false; function validateCred(arr) { let copyArr = Array.isArray(arr) ? arr.slice().reverse() : arr.toString().split("").reverse().map(Number); // Check if arr is an array, if not convert it to an array let sum = 0; let isEven = false; for (let i = 0; i < copyArr.length; i++) { let digit = parseInt(copyArr[i]); if (isEven) { digit *= 2; if (digit > 9) { digit -= 9; } } sum += digit; isEven = !isEven; } isValid = sum % 10 === 0; console.log( `The card number: ${arr} has been validated. Is it valid? Result: ${isValid}` ); return arr; } function findInvalidCards(batch) { let invalidCards = []; for (let i = 0; i < batch.length; i++) { validateCred(batch[i]); // Run validateCred() to update isValid if (!isValid) { // console.log(batch[i]); invalidCards.push(batch[i]); } } console.log('The below card numbers are not valid:'); console.log(invalidCards); return invalidCards; } function idInvalidCardCompanies(invalidNumbers) { let companies = []; // Convert single array or string to an array of arrays if (!Array.isArray(invalidNumbers[0])) { invalidNumbers = [invalidNumbers]; } else if (typeof invalidNumbers === "string") { invalidNumbers = [invalidNumbers.split("").map(Number)]; } for (let i = 0; i < invalidNumbers.length; i++) { let firstDigit = invalidNumbers[i][0]; switch (firstDigit) { case 3: if (!companies.includes("Amex")) { companies.push("Amex"); // console.log(invalidNumbers[i][0]); } break; case 4: if (!companies.includes("Visa")) { companies.push("Visa"); // console.log(invalidNumbers[i][0]); } break; case 5: if (!companies.includes("Mastercard")) { companies.push("Mastercard"); // console.log(invalidNumbers[i][0]); } break; case 6: if (!companies.includes("Discover")) { companies.push("Discover"); // console.log(invalidNumbers[i][0]); } break; default: // console.log(invalidNumbers[i][0]); console.log("Company not found"); } } return companies; } // console.log(validateCred(invalid1)); // console.log(findInvalidCards(batch)); console.log(idInvalidCardCompanies(findInvalidCards(batch))); // console.log(idInvalidCardCompanies(validateCred(invalid2))); // console.log(idInvalidCardCompanies(invalid2)); // console.log(idInvalidCardCompanies(validateCred(invalid1))); // console.log(validateCred(valid1)); // console.log(validateCred(invalid1));

Hi, Thank you for your learning materials. Just wanna share my answer here! Would be cool if you can check my code and lemme know your thoughts. Happy coding guys!