Reputation: 222571
I have the following part of code, which I do not really like:
if (a < 2){
b = 'somethingX';
} else if (a < 4){
b = 'somethingY';
} else if (a < 6){
....;
} else {
b = 'somethingZ';
}
I have something like 20 such if else statements and all of them consist of (a < SomeNumber)
conditions. Result I am assigning to b
can is not a function of a
and a < someNumber
is not in a regular interval. I would like to simplify them, but can not come up with an adequate solution.
If I would have (a === SomeNumber)
I would be able to do this easily with creating an object and accessing the value from this object (something similar to this), but here I have < sign. Is there any approach?
P.S. please do not suggest changing this to switch. I would like to make it easier to read, and based on my subjective opinion reading switch
is on the same level as if else
.
P.S.2 people asked the reason for this logic. Basically I have a thin client which returns code for error messages. They grouped in some particular way. For example everything from 1 to 8 is because there is some problem with a user. From 9 to 21 because the key is not correct. Sometimes I do not need to notify a user the exact message, so because of the grouping I can just tell generic message. Why my server is not sending the message? It is as thin as possible, so sending 7 is better then a big string.
Upvotes: 1
Views: 458
Reputation: 19294
Best way to handle it would be to use an array with the steps and associated values. You also need a default value :
var default = 'aValue';
var steps = [2, 'something', 6, 'anotherThing', 8, 'this', 10, 'that', ... ];
Then define a function that uses this array
function findSmallestMatch(val, default, steps) {
for (var i=0; i<steps.length; i+=2) if (val<steps[i]) return steps[i+1];
return default;
}
Use it with :
var res = findSmallestMatch ( 5, default, steps ); // returns 'anotherThing
Edit : If you know your input is a positive integer within a 'reasonable' range, you can pre-fill a map with the values :
var default = 'aValue';
var steps = [2, 'something', 6, 'anotherThing', 8, 'this', 10, 'that', ... ];
var matchMap = [];
for (var i=0; i<maximumValue; i+=1)
matchMap[i] = findSmallestMatch(i, default, steps);
later you can use simply with :
var res = matchMap[value];
Upvotes: 4
Reputation: 160853
You could do something like this:
var data = [[2, 'somethingX'], [4, 'somethingY'], ......];
var b = 'somethingZ'; // default value
for (var i=0; i < data.length; i++) {
if (a < data[i][0]) {
b = data[i][1];
break;
}
}
Upvotes: 2