Counting Cards -- How to make this code more DRY?

Counting Cards -- How to make this code more DRY?
0.0 0

#1

Was able to figure the task but looking at it, there’s lots of repetition. Is there a way to avoid all the || and card parameters? If you know any advanced methods to avoid that, I’d also appreciate hearing them. Thanks!

js

var count = 0;

function cc(card) {
  // Only change code below this line
  if (card == 1 || card == 2 || card == 3 || card == 4  || card == 5 || card == 6) {
    count++;
  } else if (card == 7 || card == 8 || card == 9) {
    count = count;
  } else if (card == 10 || card == 'J'|| card == 'Q' || card == 'K' || card == 'A') {
    count--;
  }


  if (count > 0) {
  return count + " Bet";
  } else {
    return count + " Hold";
  }
  
  // Only change code above this line
}

// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/counting-cards


#2

use a switch statement


#3

There are some comparison operators that would help out greatly here. For the characters, you could test against a regular expression, but best to keep things simple and figure out how you could avoid checking for letters at all.

Also, we want to make code more DRY (Don’t Repeat Yourself), not less.


#4

Do you mean more DRY?

So if you look at the first condition, you’re saying you want it to be between 1 and 6.
Second is between 7 and 9
Third is the rest of the possible cards.

You can assume that the input is correct (that the value of the card won’t be 0 or “Cat” or whatever).

So the first condition is a number less than or equal to 6 (or less than 7).
The second is less than or equal to 9 (or less than 10) - you don’t need to check its greater than 6 because the first condition catches that.
The third is anything else - you don’t need to check anything because it can only be 10 or a picture card.

You’re not actually doing anything with the second condition, so another option would be to remove it entirely, and make the last condition check if it’s a 10 or a picture card. Keeping it there makes the code a bit clearer though - you can see straightaway what’s happening.


#5

Apologies, I meant more DRY. Still learning :angel: Thanks for your help.


#6

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.