Card Counting..Using Switch

function cc(card) {
      // Only change code below this line
      switch(card){
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
          count++;
          break;
        case 10:
        case "J":
        case "Q":
        case "K":
        case "A":
          count--;
          break;
      }
      if (count > 0){
        return count + " Bet";
      } else {
        return count + " Hold";
      }
      // Only change code above this line
    }

this code perfectly works well…But i have a doubt…

  • when the card is 2 ,case 2 case 3 case 4 case 5 case 6 is executed and count is incremented by 5 ah and stopped since break arrives
  • if so then the card is 3 na…case 3,4,5,6 is executed and count is incremented by 4 ah
  • So the switch executes a statement if a case is matched and will exit only when a break is encountered…if the break is after 10 cases the 10 cases are executed without checking the condition???
    Am i right??

Then someone can tell this code using if statement

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

if the break is after 10 cases the 10 cases are executed without checking the condition???

Yes. If you omit the break statement, the next case(s) will be executed even if the evaluation does not match the case. This is called “fall-through” .

this code using if statement

const cc = card => {
    if (/[2-6]/.test(card)) {
        count++;
    } else if (/[10JQKA]/.test(card)) {
        count--;
    }
    return count > 0 ? count + " Bet" : count + " Hold";
}

@VasV Your solution works well, but you can achieve the same result without the regex, and your code would look almost the same.

var count = 0;

function cc(card) {
  if (card < 7) {
    count++;
  }

  if (card > 9 || typeof card === 'string') {
    count--
  }

  return count > 0 ? `${count} Bet` : `${count} Hold`;
  
}

This code here is very similar to your solution, but without the regex it is massively more efficient . Now my function does not go very far to stop the use of unwanted values, but if I wanted to account for that I would still highly recommend a few more conditionals rather than regex. I’m saying all this because regex does have its place, but you probably do not want to use it for simple cases like this

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