Reputation: 3
I'm working on a Freecodecamp problem and one component is taking the value of 5 cards, comparing it to a value you assign, and then presenting the current count based upon those cards.
So for example;
Cards with numbers 2,3,4,5 and 6 should incrememnt the count by 1. Cards with numbers 7,8 and 9 should do nothing. Cards 10, J, Q, K, A should decrement the count by 1.
So if I give it 5 card values, it should add them up and provide me with the count, based upon those card values.
Here is my code (I know it's sloppy, but trying to get it better);
var count = 0;
function cc(card) {
// Only change code below this line
switch (card) {
case ("A"):
--count; }
switch (card) {
case ("2"):
++count; }
switch (card) {
case ("3"):
++count; }
switch (card) {
case ("4"):
++count; }
switch (card) {
case ("5"):
++count; }
switch (card) {
case ("6"):
++count; }
switch (card) {
case ("7"):
}
switch (card) {
case ("8"):
}
switch (card) {
case ("9"):
}
switch (card) {
case ("10"):
--count; }
switch (card) {
case ("J"):
--count; }
switch (card) {
case ("Q"):
--count; }
switch (card) {
case ("K"):
--count; }
return count;
// 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');
Now I've tried using return count; return ++count; and return --count; which all give me different values. I think I might not be referencing the values of cc at the bottom to even pick up a count based on the correct values, I think I may just be issuing blind counts for the whole set of cards.
Any help is super appreciated. Thanks in advance.
Upvotes: 0
Views: 207
Reputation: 1851
Something like this:
var count = 0;
function cc(card) {//or, with ES6: cc = (card) => { (no 'function' keyword required)
switch (card) {
case ("A")://all of these 'fall through' until they hit break...be careful with this, and comment it in your code
case ("10"):
case ("J"):
case ("Q"):
case ("K"):
count -= 1;//or, count = count - 1
break;//break sends you out of the switch statement
case ("2")://same here
case ("3"):
case ("4"):
case ("5"):
case ("6"):
count += 1;
break;
//no need to do anything with 7, 8, 9
}
return count;
}
You can also add a "default" for the end in case a value other than the handled ones is sent, but in this case all you'd be doing would be count = count, which isn't necessary. Good luck!
Upvotes: 1
Reputation: 1277
See how to use switch
,case
:
https://www.w3schools.com/js/js_switch.asp
Using switch-case is quite different from using if-else which I think you are mimicking.
Upvotes: 0