The card function has been explained multiple times, and I understand it. For those who do not know it: my function receives a card parameter, which can be a number or a string. I then increment or decrement the global count variable according to the card's value 2,3,4,5,6 increments, 7,8,9 keeps it at 0, while 10, J, Q, K, A decrements it. My function then returns a string with the current count and the string "Bet" if the count is positive, or "Hold" if it is negative.
So I understand how the function is done, and FreeCodeCamp accepted my solution as technically it meets their conditions. But have a question regarding this function:
var count = 0;
function cc(card) {
if (card >= 2 && card <= 6) {
count++;
} else if (card >= 7 && card <= 9) {
count += 0;
} else {
count--;
}
if (count <= 0) {
return count + " Hold";
} else {
return count + " Bet";
}
}
console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('A'));
As I can see, the first condition is fairly simple and easy to define, so is the else if. In the third case, there are both numbers and strings involved. Does this not mean that when I put ANY string into cc, it will decrement? As anything that is not between 2 and 6, or 7 and 9, will automatically decrement? Even if the user inputs something that is not a card or is not a value from the list?
I understand that there is a list of predefined card values and names, but nevertheless, is there any better way to condition my statement to make sure that my condition will ONLY run IF the card is either 10, J, Q, K or A, and not any other value?
You can change your current else, to return and error message or just return immediately in case of the input being a non-valid card, and add another else-if to check for 10 through Ace:
if (card >= 2 && card <= 6) {
count++;
} else if (card>=7 && card <=9) {
count+= 0;
} else if (card === 10 || card === 'J' || card === 'Q' || card === 'K' || card === 'A'){
count--;
}else {
//Either just return or alert an error message and return
}
There are a number of ways you could deal with this situation. You could initially parse the input, and say assign 'J' to 11, 'Q' to 12, 'K' to 13 and 'A' to 1 (if you need to distinguish), or just a common number to that category. Everything else is an invalid input and you return immediately/post an error message. Something like:
var count = 0;
function cc(card) {
if (card == 'J' || card == 'Q' || card == 'K' || card == 'A')
card = 11;
if (card >= 2 && card <= 6) {
count++;
} else if (card>=7 && card <=9) {
count+= 0;
} else if (card >= 10 && card <= 11) {
count--; // to keep structure cleaner we use dummy 11 value
} else
//error message
if (count <= 0) {
return count + " Hold";
} else {
return count + " Bet";
}
}
cc(2); cc(3); cc(7); cc('K'); cc('A');
Also, you need to make sure to handle lower case and upper case values for the picture cards.
Define a set of allowed values and check if the value you are given is within that set using .includes(). For example:
var count = 0;
function cc(card) {
// Only change code below this line
const up = [2,3,4,5,6];
const no = [7,8,9];
const down = [10, "J", "Q", "K", "A"];
if(up.includes(card))count++;
if(down.includes(card))count--;
const str = count > 0 ? "Bet" : "Hold";
return `${count} ${str}`;
// 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');
Bear in mind this is type sensitive.
Another possibility is something like the following, which explicitly lists the changes for each card:
const counter = () => {
let count = 0
let values = {2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 0, 8: 0,
9: 0, 10: -1, J: -1, Q: -1, K: -1, A: -1}
return (card) => {
const change = values[card] || 0 // no change if card is, say, 'XYZ' or 'Joker'
count += change
return count <= 0 ? 'Hold' : 'Bet'
}
}
const cc = counter();
console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('A'));
For a list as short as thirteen values, I think this sort of explicit list is cleaner.
This also encapsulates the count variable in a closure. I find that cleaner than a global variable.
Where the comment talks about jokers, you might want some more robust error-handling:
if (!(card in values)) {throw 'Bad card'}
const change = values[card]
You could use a regular expression at the very top of your function to skip all the conditionals and return a handy message if the argument passed in doesn't match a valid card:
// Check if card is valid
var cardRegex = /^(10|[2-9AJQK])$/i;
if (!cardRegex.test(card)) {
return "Invalid Card";
}
So, in the context of your code, it would look like:
var count = 0;
function cc(card) {
// Check if card is valid
var cardRegex = /^(10|[2-9AJQK])$/i;
if (!cardRegex.test(card)) {
return "Invalid Card";
}
if (card >= 2 && card <= 6) {
count++;
} else if (card >= 7 && card <= 9) {
count += 0;
} else {
count--;
}
if (count <= 0) {
return count + " Hold";
} else {
return count + " Bet";
}
}
// Valid inputs
console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('a'));
// Invalid inputs
console.log(cc('e'));
console.log(cc('L'));
console.log(cc(0));
My solution for Basic JavaScript: Counting Cards
function cc(card) {
// Only change code below this line
if(card >= 2 && card <= 6) {
count++;
} else if (card === 10 ||card === 'J' || card === 'Q' || card === 'K' || card === 'A') {
count = count - 1;
}
if (count > 0) {
return count + ' Bet';
}
return count + ' Hold';
// Only change code above this line
}
My solution, based on what we learned so far.
Maybe it isnĀ“t the best, but it also works.
var count = 0;
function cc(card) {
// Only change code below this line
switch(card){
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break
case 7:
case 8:
case 9:
count = count;
break
case 10:
case 'J':
case 'Q':
case 'K':
case 'A':
count--;
break;
}
if (count <=0) {
return count + ' Hold';
}
else {
return count + ' Bet'
}
// Only change code above this line
}
console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('A'));
let count = 0;
function cc(card) {
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--;
}
if (count > 0) {
return count + " Bet";
} else {
return count + " Hold";
}
}
I'm taking an introductory course on Javascript at my college and in my assignment, I had to write a function that took a value passed into the parameter and compares it through a switch statement. This is what I did:
function grader(mark) {
switch (mark) {
case (mark >= 80 && mark <= 100) :
return 'A';
break;
case (mark >= 70 && mark <= 79) :
return 'B';
break;
case (mark >= 60 && mark <= 69) :
return 'C';
break;
case (mark >= 50 && mark <= 59) :
return 'D';
break;
case (mark >= 0 && mark <= 49) :
return 'F';
break;
}
}
But the error I'm getting on scratchpad is this:
Exception: SyntaxError: expected expression, got '>'
#Scratchpad/2:3
*/
/*
undefined
*/
What does it mean when an operand is undefined?
NO switch cases cannot check a value in the range.
switch (expression) {
case value1:
//Statements executed when the
//result of expression matches value1
[break;]
case value2:
//Statements executed when the
//result of expression matches value2
[break;]
That clearly tells that the case should be a specific value.
You should go with tradational if else if
if (mark >= 80 && mark <= 100){
return 'A';
}
else if (mark >= 70 && mark <= 79) {
return 'B';
}
How can I convert this if statement into switch case? I tried to declare the variable like this:
myAge = parseFloat(prompt("Enter you age: "));
if(myAge <18) {
alert("You cant not vote at this " +myAge);
} else if (myAge >18) {
alert("Vote wisely, you are " +myAge "years old!");
} else {
alert("Invalid age");
}
Give condition if age < 18,
You can't not vote at this age
If age> = 18, You can vote at this age.
Else invalid age.
var myAge = parseFloat(prompt("Enter you age: "));
switch (true) {
case myAge < 18:
alert("You cant not vote at this " + myAge);
break;
case myAge >= 18:
alert("Vote wisely, you are " + myAge + " years old!");
break;
default:
alert("Invalid age");
}
Answering your "how can I convert it to switch" question, you can implement a function which makes C-style comparison and returns -1, 0 or 1 as the result of comparing.
The example below uses a setInterval to emulate multiple different cases. This is only for the example.
function compareTo(a, b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
function EvaluateAge() {
// Generate a random age between 10 and 40
var myAge = Math.floor((Math.random() * 30) + 10);
switch (compareTo(myAge, 18)) {
case -1:
console.log(myAge, " less than 18");
break;
case 0:
console.log(myAge, " equal to 18");
break;
case 1:
console.log(myAge, "more than 18");
break;
}
}
// Example only
setInterval(EvaluateAge, 1000);
Another way is to use JS switch ability to use true in switch-condition:
var myAge = 16;
switch (true) {
case myAge < 18:
console.log("less than 18");
break;
case myAge === 18:
console.log("equal to 18");
break;
case myAge > 18:
console.log("more than 18");
break;
}
However, it doesn't look good and it is a good idea to avoid this usage.
Actually, your if looks good and imho you don't need to convert it to switch - it won't increase readability / maintainability of your code.
Not sure why you would want to do this instead of concise if statements, but you can like so:
var myAge = parseFloat(prompt("Enter you age: "));
switch (true) {
case myAge < 18:
alert("You cant not vote at this " + myAge);
break;
case myAge > 18:
alert("Vote wisely, you are " + myAge + " years old!");
break;
default:
alert("Invalid age");
}
Note, that you are not capturing a value of 18 which I'll just assume was intentional but worth pointing out to you and, also, you were missing a + concatenating your second alert so your original example wouldn't even have executed.
I have a long list of postal codes I have to validate.
Link to postal codes
As you can see it's quite random there is no real order.
I tried making a switch and put in everything by hand like so:
switch (true) {
case ($(this).val().length < 5) :
console.log("not filled out");
break;
case (number >= 1001 && number <= 6999):
validated = true;
error = false;
break;
case (number >= 8001 && number <= 34999):
validated = true;
error = false;
break;
case (number >= 36001 && number <= 37999):
validated = true;
error = false;
break;
default:
console.log("error");
error = true;
}
But I quickly realised this would be a stupid long code.
What would be a better way to validate all the ranges of postal codes?
You can reduce your switch for something like this
switch (true) {
case ($(this).val().length < 5) :
console.log("not filled out");
break;
case (number >= 1001 && number <= 6999):
case (number >= 8001 && number <= 34999):
case (number >= 36001 && number <= 37999):
validated = true;
error = false;
break;
default:
console.log("error");
error = true;
}
You can then add the list of rules you need
Am I writing the correct switch case with conditions?
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
alert('31');
break;
default:
alert('>41');
}
For some reason, the alert does not occur when the conditions are matched!
A switch works by comparing what is in switch() to every case.
switch (cnt) {
case 1: ....
case 2: ....
case 3: ....
}
works like:
if (cnt === 1) ...
if (cnt === 2) ...
if (cnt === 3) ...
Therefore, you can't have any logic in the case statements.
switch (cnt) {
case (cnt >= 10 && cnt <= 20): ...
}
works like
if (cnt === (cnt >= 10 && cnt <= 20)) ...
and that's just nonsense. :)
Use if () { } else if () { } else { } instead.
You should not use switch for this scenario. This is the proper approach:
var cnt = $("#div1 p").length;
alert(cnt);
if (cnt >= 10 && cnt <= 20)
{
alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
alert('31');
}
else
{
alert('>41');
}
This should work with this :
var cnt = $("#div1 p").length;
switch (true) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
break;
default:
alert('>41');
}
Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.
Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.
$('.next').click(function(){
var imageToSlide = $('#imageSprite'); // Get id of image
switch(true) {
case (imageToSlide.hasClass('pos1')):
imageToSlide.removeClass('pos1').addClass('pos2');
break;
case (imageToSlide.hasClass('pos2')):
imageToSlide.removeClass('pos2').addClass('pos3');
break;
case (imageToSlide.hasClass('pos3')):
imageToSlide.removeClass('pos3').addClass('pos4');
break;
case (imageToSlide.hasClass('pos4')):
imageToSlide.removeClass('pos4').addClass('pos1');
}
}); `
What you are doing is to look for (0) or (1) results.
(cnt >= 10 && cnt <= 20) returns either true or false.
--edit--
you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length.
--edit--
function date_conversion(start_date){
var formattedDate = new Date(start_date);
var d = formattedDate.getDate();
var m = formattedDate.getMonth();
var month;
m += 1; // JavaScript months are 0-11
switch (m) {
case 1: {
month="Jan";
break;
}
case 2: {
month="Feb";
break;
}
case 3: {
month="Mar";
break;
}
case 4: {
month="Apr";
break;
}
case 5: {
month="May";
break;
}
case 6: {
month="Jun";
break;
}
case 7: {
month="Jul";
break;
}
case 8: {
month="Aug";
break;
}
case 9: {
month="Sep";
break;
}
case 10: {
month="Oct";
break;
}
case 11: {
month="Nov";
break;
}
case 12: {
month="Dec";
break;
}
}
var y = formattedDate.getFullYear();
var now_date=d + "-" + month + "-" + y;
return now_date;
}
Switch case is every help full instead of if else statement :
switch ($("[id*=btnSave]").val()) {
case 'Search':
saveFlight();
break;
case 'Update':
break;
case 'Delete':
break;
default:
break;
}
Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.
What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.
Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.
Like follow:
switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
alert('10');
break;
case (cnt >= 21 && cnt <= 30 && cnt):
alert('21');
break;
case (cnt >= 31 && cnt <= 40 && cnt):
alert('31');
break;
default:
alert('>41');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>