Switch Statement with range value - javascript

I'm writing swtich javascript switch statement in JS file and figured out the problem whole day still cannot find the solution.
Here is my javascript file written in jQuery :
var percent = 20;
var widthbytes;
switch(percent)
{
case 0:
widthbytes=0;
break;
case (percent > 10 && percent < 20):
widthbytes=16;
break;
case (percent >=20 && percent < 30):
widthbytes=30;
break;
default:
widthbytes=0;
break;
}
average.width(widthbytes);
It always return to default instead of 30. Anything wrong with my codes ?

switch statement only check the value of variable and then give the result according to that value so your expression
case (percent > 10 && percent < 20):
return boolean value which is not not comparable to variable value. Use if-else to get the job done.

just make a bit change in your code.
You have switch(percent)**in your code, only change for this ***switch(true)*.
The reason for that is because the switch statement return a boolean value, this is why we need they have the same comparation, i.e. boolean vrs boolean.
For example the case 10: return one value; true or false.

I can't see a problems with #Carlos Marin's answer. This works:-
var percent = 10; //test values-> 10, 11, 19, 20, 21, 29, 30
var widthbytes;
switch(true){
// case 0:
// widthbytes=0;
// break;
case (percent > 10 && percent < 20):
widthbytes=16;
break;
case (percent >=20 && percent < 30):
widthbytes=30;
break;
default:
widthbytes=0;
break;
}
console.log(widthbytes);

switch statements don't work like that. Your second case is checked like this: if (percent == (percent > 10 && percent < 20)) ..., which will not yield the desired result.
You could use an if / elseif / else construct:
if (percent === 0) {
widthbytes = 0;
} else if (percent > 10 && percent < 20 {
widthbytes = 16;
} else if (percent >= 20 && percent < 30 {
widthbytes = 30;
} else {
widthbytes = 0;
}
Or you could use a function that turns the ranges into constants:
function getRange(percent) {
return Math.floor(percent/10);
}
switch(getRange(percent)) {
case 10:
widthbytes = 16;
break;
case 20:
widthbytes = 30;
break;
default:
widthbytes = 0;
}
Note that to get a cleaner implementation i assimilated your original case 0: into the default, since they both do the same thing. If that is not desirable, you need to change the getRange function to no longer return the same range for 0 as for any number between 0 and 10.

Related

Why this switch isn't giving any output? [duplicate]

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>

Why "if" works but "switch" doesn't work?

// It is simple code
var num = prompt("put number");
// This way is not worked
switch (num) {
case num > 0:
console.log("num++");
break;
case num < 0:
console.log(num-2);
break;
}
// But this worked
if (num > 0){
console.log(num++);
} else if (num < 0){
console.log(num -2);
}
My first way by "switch" is not worked but "if" method worked.
I tried all of thing for changing code or other ways but the same result.
Please guys help me.
Because the statement num > 0 inside you case will return true or false.
If you do this:
switch (true) {
case num > 0:
console.log("num++");
break;
case num < 0:
console.log(num-2);
break;
}
It will work.
Cases cannot be expressions, you must normalize your input first.
Although it is valid to place an expression in a case, in this scenario a more tried-and-true way of dealing with this is to first normalize your input first.
You can determine direction for example:
var num = parseInt(prompt("put number"), 10);
var direction = num < 0 ? -1 : 1;
switch (direction) {
case 1:
console.log("num++");
break;
case -1:
console.log(num - 2);
break;
}
The switch acts as a case switcher, meaning you cannot make comparisons to create cases, just list cases by case, and perform some function from this case. The if / else structure is suitable for making comparisons, as the expected result in the if call is always a boolean.
Example:
const a = 1;
if (a === 1) {
console.log('hello');
} else {
console.log('sad');
switch (a) {
case 1 : console.log('hello'); break;
default: console.log('sad'); break;
In your case, I recommend using if/else if/else, as it is more recommended.

Javascript operators in switch case

I'm creating a panel and there are stats for memory, CPU and HDD. I'm using a switch statement and in the case method, I'm putting the current usage of CPU, memory and HDD.
However, the problem is that I'm using operators and I don't know which operator to use because I've tried all of them and I didn't get the results that I expected.
And this is the code: https://pastebin.com/YaxCm0Be
switch(true){
case (mem_percent_get <= 0.01):
var mem_progress_color = 'progress-bar-primary';
break;
case (mem_percent_get <= 33):
var mem_progress_color = 'progress-bar-success';
break;
case (mem_percent_get <= 66):
var mem_progress_color = 'progress-bar-warning';
break;
case (mem_percent_get <= 80):
var mem_progress_color = 'progress-bar-danger';
break;
default:
mem_progress_color = 'progress-bar-theme';
}
switch(true){
case (cpu_percent_get <= 33):
var cpu_progress_color = 'progress-bar-success';
break;
case (cpu_percent_get <= 66):
var cpu_progress_color = 'progress-bar-warning';
break;
case (cpu_percent_get <= 80):
var cpu_progress_color = 'progress-bar-danger';
break;
default:
cpu_progress_color = 'progress-bar-primary';
}
switch(true){
case hdd_percent_get <= 0.01:
var hdd_progress_color = 'progress-bar-primary';
break;
case hdd_percent_get <= 30:
var hdd_progress_color = 'progress-bar-success';
break;
case hdd_percent_get <= 60:
var hdd_progress_color = 'progress-bar-warning';
break;
case hdd_percent_get <= 80:
var hdd_progress_color = 'progress-bar-danger';
break;
default:
hdd_progress_color = 'progress-bar-theme';
}
Well, my first comment is to not use a switch in this case. What you are doing is essentially if () { } else if() {} blocks. You should be using switch when you have a value that you want to strictly check against. I suggest looking into at the MDN docs for switch.
Secondly, from what I can gather is that for the memory, you need it to be red when the value is 1696 / 2098 (80.83%). All of your if/elseif cases rely on <= which would mean that the value must be less than or equal to the number on the right of the equation. In your case, you are looking for <= 80, and without seeing how you calculate mem_percent_get (if it is in the pastebin, I'm unable to open that on my current network), you're value is likely above 80.
For your danger, you likely want 80-100+% as being red, so you should be using >= or greater than or equal to operator.
MDN has an excellent resources on comparison operators.
Created a getClassName method that accepts a percent and will return a className:
const getClassName = percent => {
switch(true){
case (percent <= 0.01):
return 'progress-bar-primary';
case (percent <= 33):
return 'progress-bar-success';
case (percent <= 66):
return 'progress-bar-warning';
case (percent <= 80):
return 'progress-bar-danger';
default:
return 'progress-bar-theme';
}
}
console.log('0: ', getClassName(0));
console.log('40: ', getClassName(40));
console.log('50: ', getClassName(50));
console.log('80: ', getClassName(80));
console.log('100: ', getClassName(100));

How to create a switch comparator in JS?

is there a way to create a switch comparator like this one?
switch (item) {
case (item<= 10):
money += 25;
$('#money').html(money);
break;
case (item > 10 && item <= 20):
money += 50;
$('#money').html(money);
break;
}
may be this:
item = YourValue;
switch (true) {
case (item <= 10):
money += 25;
$('#money').html(money);
break;
case (item > 10 && item <= 20):
money += 50;
$('#money').html(money);
break;
}
The expressions in the case statements will evaluate to true or false, and if that matches the switch condition,
but as per my suggestion you should go with if...else if...else statement for this kind of business logic.
Simple answer: No. Switch..case statements don't work like this. You would need an if & else if statement:
if (item <= 10)
{
money += 25;
$('#money').html(money);
}
else if (item > 10 && item <= 20)
{
money += 50;
$('#money').html(money);
}
You can use the if else instead of switch
if (item <= 10)
{
money += 25;
$('#money').html(money);
}
else if (item > 10 && item <= 20)
{
money += 50;
$('#money').html(money);
}

JavaScript switch statement 1-100

I am trying to write a JavaScript switch where the user enters a number from 1-100 and they receive a message based on what range the number falls into. This is what I have written so far.
I am doing this for an intro to programing class, and I don't fully understand how to get this to work, my problem is that I can't figure out how to show a range, ie: 1-25,
<script>
var number = prompt("Enter 1-100");
switch(number)
{
case 1-25:
document.write("1-25");
break;
case 26-50;
document.write("26-50");
break;
case 51-100:
document.write("51-75");
break;
case "4":
document.write("76-100");
break;
}
</script>
Just figuring it out with a little math is probably a better approach :
var number = prompt("Enter 1-100"),
message = ['1-25', '26-50', '51-75', '76-100'];
document.write(message[Math.ceil(number/25)-1])
FIDDLE
Divide the returned number with 25, round up to nearest whole number, which gives you 1,2,3 ... etc, and since array indices starts at zero, subtract 1.
EDIT:
If you have to do a switch, you'd still be better off with a little math, and not writing a hundred case's :
var number = prompt("Enter 1-100");
number = Math.ceil(number / 25 );
switch(number) {
case 1:
document.write("1-25");
break;
case 2:
document.write("26-50");
break;
case 3:
document.write("51-75");
break;
case 4:
document.write("76-100");
break;
}
FIDDLE
You can use conditions with switch like this:
var number = prompt("Enter 1-100");
switch (true) {
case number >= 1 && number <= 25:
alert("1-25");
break;
case number >= 26 && number <= 50:
alert("26-50");
break;
case number >= 51 && number <= 75:
alert("51-75");
break;
case number >= 76 && number <= 100:
alert("76-100");
break;
}
http://jsfiddle.net/dfsq/T3zJR/
You cannot use ranges in switch statements. To check whether a value is contained in a range, you need to compare against lower and upper bounds:
number = parseInt(number, 10);
if (number >= 1 && number <= 25)
document.write("1-25");
else if (number >= 26 && number <= 50)
document.write("26-50");
else if (number >= 51 && number <= 75)
document.write("51-75");
else if (number >= 75 && number <= 100:
document.write("76-100");
else
document.write(number+" is not a valid number between 1 and 100");
Of course, as the number of if-elses grows, you should look for an alternative. An algorithmic solution would be the simplest (dividing by 25 and rounding to find the 25-multiple interval the number is contained in):
number = parseInt(number, 10);
var range = Math.floor((number-1)/25);
if (range >= 0 && range < 4)
document.write( (1+range*25) + "-" + (1+range)*25);
If you can't use that (for example because of erratic intervals) a for-loop (or even a binary search) over an array of interval boundaries would be the way to go (as demonstrated by #jfriend00).
If you want simple ranges of 25, you can do this:
if (number < 1 || number > 100)
document.write("out of range");
else {
var low = Math.floor(number / 25) * 25 + 1;
var high = low + 24;
document.write(low + "-" + high);
}
You need a single value to match a case, or a switch takes longer than if elses...
you can get the range before switching-
var number = prompt("Enter 1-100", '');
var s= (function(){
switch(Math.floor((--number)/25)){
case 0: return "1-25";
case 1: return "26-50";
case 2: return "51-75";
default: return "76-100";
}
})();
alert(s);
Here's a table driven approach that allows you to add more items to the table without writing more code. It also adds range checking.
<script>
var breaks = [0, 25, 50, 75, 100];
var number = parseInt(prompt("Enter 1-100"), 10);
var inRange = false;
if (number) {
for (var i = 1; i < breaks.length; i++) {
if (number <= breaks[i]) {
document.write((breaks[i-1] + 1) + "-" + breaks[i]);
inRange = true;
break;
}
}
}
if (!inRange) {
document.write("Number not in range 1-100");
}
</script>

Categories