Convert Nested If Statements To More Elegant Switch?
how can i convert this nested if statement to something more readable and 'elegant'? if(speed==0){ othvalue=0; }else { if(speed>value1864cmn){
Solution 1:
You can use "match" construct:
var othvalue = (speed == 0) ? 0
: (speed <= 10) ? 10
: (speed <= 20) ? 20
: (speed <= 30) ? 30
: 40;
Solution 2:
You don't need to nest this, nor convert it to a switch statement. Just put the if
right next to the else
.
For instance:
if(speed==0){
othvalue=0;
} elseif(speed>value1864cmn){
othvalue=value1864cmn;
} elseif {
...
Solution 3:
if (speed == 0) {
othvalue = 0;
} elseif (speed > value1864cmn) {
othvalue = value1864cmn;
} elseif (speed > value1746cmn) {
othvalue = value1746cmn;
} elseif (speed > value1628cmn) {
othvalue = value1628cmn;
} elseif (speed > value1510cmn) {
othvalue = value1510cmn;
} elseif (speed > value1392cmn) {
othvalue = value1392cmn;
} elseif (speed > value1274cmn) {
othvalue = value1274cmn;
} elseif (speed > value1156cmn) {
othvalue = value1156cmn;
} elseif (speed > value1038cmn) {
othvalue = value1038cmn;
} elseif (speed > value920cmn) {
othvalue = value920cmn;
};
Solution 4:
if (speed == 0) {
othvalue = 0;
} else {
var values = [
value1746cmn, value1628cmn, value1510cmn, value1392cmn, value1274cmn,
value1156cmn, value1038cmn, value920cmn
];
for (var i in values) {
if (speed > values[i]) {
othvalue = values[i];
break;
}
}
}
Solution 5:
// I don't know about elegant, but stepping through an array is pretty quick.
functionsetSpeedValue(speed){varL=9,values= [0, 920, 1038, 1156, 1274, 1392, 1510, 1628, 1746, 1864];while(values[L]>speed)--L;return'value'+values[L]+'cmn';}alert(setSpeedValue(1040))
Post a Comment for "Convert Nested If Statements To More Elegant Switch?"