Using JavaScript operators in a switch statement with event.code [duplicate] - javascript

This question already has answers here:
Switch statement for multiple cases in JavaScript
(26 answers)
Closed 3 years ago.
I have a switch statement in which I try to map keyboard shortcuts to a horizontal full page scrolling:
Space Bar or Page Down or Right Arrow
scrolls forward
Page Up or Left Arrow scrolls
backward
Home or Up Arrow goes to the beginning
of the page
End or Down Arrow scrolls to the end
of the page
Here is my attempt, which isn’t working:
switch (event.code) {
case "Space" || "PageDown" || "ArrowRight": {
scrollAmount += window.innerWidth
break
}
case "PageUp" || "ArrowLeft": {
scrollAmount -= window.innerWidth
break
}
case "Home" || "ArrowUp": {
scrollAmount = 0
break
}
case "End" || "ArrowDown": {
scrollAmount = container.scrollWidth
break
}
}
How do I propely use the operators in this case?

You should specify each case separately:
switch (event.code) {
case "Space":
case "PageDown":
case "ArrowRight": {
scrollAmount += window.innerWidth
break
}
case "PageUp":
case "ArrowLeft": {
scrollAmount -= window.innerWidth
break
}
case "Home":
case "ArrowUp": {
scrollAmount = 0
break
}
case "End":
case "ArrowDown": {
scrollAmount = container.scrollWidth
break
}
}

Related

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));

Why does this switch statement not work? [duplicate]

This question already has answers here:
Expression inside switch case statement
(8 answers)
Closed 6 years ago.
I created a switch statement but everything seems to be falling into the default condition. If I rewrite this in an if/else format it works correctly. Can anyone explain why this is? Thanks!
Doesn't work:
switch(delta){
case (delta<10):
xsmall++;
break;
case (delta>= 10 && delta< 50):
small++;
break;
case (delta>= 50 && delta<250):
med++;
break;
case (delta>= 250 && delta<1000):
large++;
break;
case (delta>= 1000):
xlarge++;
break;
default:
unknown++;
}
Works successfully:
if(delta<10)
xsmall++;
else if(delta>= 10 && delta < 50)
small++;
else if(delta >= 50 && delta < 250)
med++;
else if(delta >= 250 && delta <1000)
large++;
else if(delta >= 1000)
xlarge++;
else
unknown++;
This will work:
switch(true){
case (delta<10):
xsmall++;
break;
case (delta>= 10 && delta< 50):
small++;
break;
case (delta>= 50 && delta<250):
med++;
break;
case (delta>= 250 && delta<1000):
large++;
break;
case (delta>= 1000):
xlarge++;
break;
default:
unknown++;
}
Reason: You need to pass boolean to the switch statement as all your cases will return boolean and not a number

Why isn't my jquery switch statement working?

I am trying a jquery (javascript) switch statement with some simple operators but it isn't working as expecting
console.log('test '+getShippingCost(8));
function getShippingCost(shop_qty) {
shipping_costs = 0;
dest = $("input[name='dest']").val();
console.log(dest);
if (dest === 'DOMESTIC') {
switch (shop_qty) {
case (shop_qty > 4):
shipping_costs = 3.5;
break;
case (shop_qty <= 4):
shipping_costs = 2;
break;
}
console.log('domestic shipping '+shipping_costs);
}
if (dest === 'INT') {
switch (shop_qty) {
case (shop_qty > 4):
shipping_costs = 4.5;
break;
case (shop_qty <= 4):
shipping_costs = 3;
break;
}
}
return shipping_costs;
}//end function
see see jsfiddle
To use conditions for the cases in a switch, you would look for a true value among the cases:
switch (true) {
case (shop_qty > 4):
shipping_costs = 3.5;
break;
case (shop_qty <= 4):
shipping_costs = 2;
break;
}
As the second case is the inverse of the first, you can just use default for that:
switch (true) {
case (shop_qty > 4):
shipping_costs = 3.5;
break;
default:
shipping_costs = 2;
break;
}
Such a construct fits better when you have several conditions. You should consider if an if statement would be a better fit in this case:
if (shop_qty > 4) {
shipping_costs = 3.5;
} else {
shipping_costs = 2;
}
As both cases assign a value to the same variable, you can also write it using the conditional operator:
shipping_costs = shop_qty > 4 ? 3.5 : 2;
Cases in switch statements evaluate values, not boolean expressions: See Here.
You can put the logic suggested by your attempted use of the switch statement in a ternary expression, e.g.:
shipping_costs = (shop_qty > 4) ? 3.5 : 2;
Switch doesn't work by evaluating boolean expressions. Switch evaluates an initial expression and then tries to match the cases to that expression using strict equality. So you can't do
case(x<4.5):
You have to do something like
case 4:
Use if, else if, else statments instead.

How to change image on key release

I'm working on a little game using HTML5 canvas and javascript. Now what I am trying to do is to make an image move from left to right and when pressing a key it changes image to make it look more like it is moving.
Now I got that working but I'm kind of stuck. The code is that when you press the left key he changes the player.image to player.imgLeft and when releasing change it back to the normal image.
The pressing works but the releasing doesn't.. What am I doing wrong?
Here is in short the code
// Things to do when keys are down
function onKeyDown(event)
{
if (event.keyCode >= 37 && event.keyCode<=39)
event.preventDefault(); // prevent arrow keys from scrolling the page
switch (event.keyCode) {
case 37: player.vx = -1; player.image = player.imgLeft; break; // left key
case 38: player.vy = -1; break; // up key
case 39: player.vx = 1; player.image = player.imgRight; break; // right key
}
}
// Things to do when keys are up
function onKeyUp(event)
{
switch (event.keyCode) {
case 37: case 39: player.vx = 0; player.imgLeft = player.image; break; // left or right key released
case 38: player.vy = 0; break; // up or down key released
}
}
Modify like this if you have your original image in player.original.. Onkeyup event you should use like this ...
function onKeyUp(event)
{
switch (event.keyCode) {
case 37: case 39: player.vx = 0; player.image = player.original; break; // left or right key released
case 38: player.vy = 0; break; // up or down key released
}
}
When you press the key, you do
player.image = player.imgLeft
and when you release, you do
player.imgLeft = player.image;
which does nothing, as both variables hold the same value. You need a third variable to store the original player.image value.
Remember:
If you are using onkeydown="return onKeyDown(event)" you need onkeyup="return onKeyUp(event)".

how to use two onkeydown events at the same time?

I'm trying to build a pong game, and I want the boards to be able to move simultaneously (one with the 's' and 'w' and the other with the up and down arrows).
function movePlayer1(event) {
if (player1.y > 7.5 && player1.y < 390) {
switch (event.keyCode) {
case 83: player1.y += player1.v;
break;
case 87: player1.y -= player1.v;
break;
}
}
else if (player1.y <= 7.5) {
switch (event.keyCode) {
case 83: player1.y += player1.v;
break;
}
}
else if (player1.y >= 390) {
switch (event.keyCode) {
case 87: player1.y -= player1.v;
break;
}
}
}
document.addEventListener("keydown", movePlayer1, false);
function movePlayer2() {
if (player2.y > 7.5 && player2.y < 390) {
switch (event.keyCode) {
case 40: player2.y += player2.v;
break;
case 38: player2.y -= player2.v;
break;
}
}
else if (player2.y <= 7.5) {
switch (event.keyCode) {
case 40: player2.y += player2.v;
break;
}
}
else if (player2.y >= 390) {
switch (event.keyCode) {
case 38: player2.y -= player2.v;
break;
}
}
}
document.addEventListener("keydown", movePlayer2, false);
I've tried putting them in one function instead but it didn't help.
There are two things make you code behave not as you expect.
Autorepeating works only for last pressed key. Say if you press "A" and hold it autorepeating will generate keydown events for "A". But if you press "B" and hold both autorepeating will generate sequential keydown automatically for "B" only. On the other side I believe for MacOS it will not autorepeat at all so better not rely on this.
But actually "keyup" are triggered correctly even if mutliple keys were pressed and are hold.
So you can refactor your code: instead of relying on keyup/keydown only you need some timer and each player model will be
{
directionIsUp: true | false,
isMoving: true | false
}
So on keydown you are setting appropriate direction and make isMoving to be true. And on keyup you are making isMoving to be false.
And timer will re-render your battlefield accordingly to those models - either moving player or keeping it at the same place.

Categories