JavaScript Counting Cards works just fine but doesn't pass the challenge

JavaScript Counting Cards works just fine but doesn't pass the challenge
0

#1

Hey,
my problem is not that it wasn’t working. It works just fine and it always prints out the demanded answer. I don’t pass the challenge though? What did I do wrong? I thought that I had fulfilled all requirements specified by the hints.

Here’s my code:

var count = 0;

function cc(card) {
  // Only change code below this line
  for (let i = 0; i < card.length; i++) {
    switch(card[i]) {
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
        count++;
        break;
      case 7:
      case 8:
      case 9:
        count += 0;
        break;
      case 10:
      case 'J':
      case 'Q':
      case 'K':
      case 'A':
        count--;
        break; 
    }
  }

  if (count > 0) {
    count += " Bet";
  } else {
    count += " Hold";
  }

  return count;
  
  // Only change code above this line
}

#2

You should not be adding string values to count.

  if (count > 0) {
    count += " Bet";
  } else {
    count += " Hold";
  }
  console.log(count);
  return count;

I added a console.log statement above. Try it and see what you are adding to count. Remember, count is global, so it will retain it’s value between tests.


#3
for (let i = 0; i &lt; card.length; i++)   // can you explain what this loop does
{ switch(card[i]) {  // is card an array?

#4

Thank You!
Instead of adding the string to count I just print it out alongside count. Like this:

if (count > 0) {
    return count + " Bet";
  } else {
    return count + " Hold";
  }

Now it passes the challenge :slight_smile:


#5

I used this loop so I could specify the card sequence within the card parameter itself (an array). I didn’t see any rules forbidding this so I figured it was legitimate.
The loop iterates(?) through my card-array so the switch statement is performed on each element of the array.


#6

That is what I was thinking. That would work as a valid solution to a card counting algorithm. But in order to pass the assertion tests your function needs to take only one card per function call like this cc('K'); and then return an updated assessment on whether you should bet or hold.

The assertions will test a sequence of these function calls like cc(2); cc(3); cc(7); cc('K'); cc('A'); and then check to see that the last one returns the correct count and statement.

For example, the first test

cc(2); // returns 1 Bet
cc(3); // returns 2 Bet
cc(4); // returns 3 Bet
cc(5); // returns 4 Bet
cc(6); // return 5 Bet
// assertion checks that last call is '5 Bet'