I am trying to create a simplistic function which uses a switch statement to return a weighted number. For my use case, the solution is most befitting, however I am getting "undefined" as the result for no obvious reasons. If anyone could point out the mistake, I'm making.
function randomCase() {
let n = Math.floor(Math.random() * 100);
switch (n) {
case n < 70:
return 1;
case n < 80:
return 2;
case n < 90:
return 3;
case n < 100:
return 4;
}
}
temp = randomCase();
console.log(temp);
I tried to debug with Chrome developer tool and figure out what might be causing this, but of no avail. It seems there is something obvious I'm missing. (Still learning JS)
As VLAZ mentioned in the comments, a switch statement checks for equality.
You'll want to use an if statement instead:
function randomCase() {
let n = Math.floor(Math.random() * 100);
if (n < 70) {
return 1;
} else if (n < 80) {
return 2;
} else if (n < 90) {
return 3;
} else if (n < 100) {
return 4;
}
}
temp = randomCase();
console.log(temp);