1

Please check the code below

   if( x > 10 && x <= 100 ){
      do.something(1)
    }
    else if ( x > 100 && x <= 1000 ) {
      do.something(2)
    }
    else if ( x > 1000 && x <= 10000 ) {
      do.something(3)
    }
    else if ( x > 10000 && x <= 100000 ) {
      do.something(4)
    }
  1. Is the any better alternative to this if/else or switch chain?
  2. Can we make it configurable - so that I can keep all the conditions and corresponding action in one data-structure and write code that can pick all the conditions from that structure and do actions accordingly? This will help me keep all the conditions in a separate conf file and it will be easy to just make the edits to that and not touch the code

NOTE: These ranges may be inconsistent like 100 - 200, 345 - 956, 1000 - 1200

  • @noobs, Its just an example. I am making it different now! – joginder singh Jul 13 '18 at 11:10
  • 1
    The conditions `x > 100` and `x > 1000` and `x > 10000` are redundant. When the code enters those paths those conditions are always true (because they are on the `else` paths of `x <= 100` and so on.) – axiac Jul 13 '18 at 11:34
  • @noobs, All the answers mentioned in that answer use consistent ranges. Ranges in my case can be inconsistent! – joginder singh Jul 13 '18 at 11:34

3 Answers3

2

You could take an array and use the shor circuit of Array#some for a found range.

var value = 300;
    values = [
        [10, () => undefined],
        [100, () => do.something(1)],
        [1000, () => do.something(2)],
        [10000, () => do.something(3),
        [100000, () => do.something(4)]
    ];

values.some(([v, f]) => {
    if (value <= v) {
        f();
        return true;
    }
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

This would make it configurable.

const cond = [
  {min: 10, max: 100, val: 1},
  {min: 100, max: 1000, val: 2},
  {min: 1000, max: 10000, val: 3},
  {min: 10000, max: 100000, val: 4},
]

do.something(cond.filter(c => x > c['min'] && x < c['max'])[0]['val'])
C14L
  • 12,153
  • 4
  • 39
  • 52
-1
  1. I think it is fastest way, but not for IE check here
  2. Yes, you can write it for example in .json or .env file, and read it.
Michał Tkaczyk
  • 732
  • 5
  • 18