Home > database >  how to replace multiple if else with a simpler expression
how to replace multiple if else with a simpler expression

Time:05-19

I have defined multiple intervalls [0, 20[,[20, 70[, [70, 200[, [200, 500[, [500, 10000[, [1000, infinity[. For a given value of x we get a value y in [0,1,2,3,4,5] with [0, 20[ corresponding to 0 etc... The basic solution is to use if statements like:

if (x>=0 && x<20){
  y = 0
} 
if (x>=20 && x<70){
  y = 1
}
.
.
.

Ist there other solutions for this task(less code)? I am using this code in nodejs

CodePudding user response:

Use else if, then you don't need to check the lower bounds, because the previous check already handled that.

if (x < 20) {
    y = 0;
} else if (x < 70) {
    y = 1;
} ...

or you can put the limits in an array, and loop until you go past the limit.

const limits = [20, 70, 200, ...];
let y;
for (y = 0; y < limits.length && x < limits[y]; y  ) {};

CodePudding user response:

You can use a logic like this:

const intervals = [
    { from: 0, to: 20},
    { from: 20, to: 70},
    { from: 70, to: 200},
    { from: 200, to: 500},
    { from: 500, to: 1000},
    { from: 1000, to: Number.POSITIVE_INFINITY}
];

function findInterval(x) {
    for (let i in intervals) {
        if (x >= intervals[i].from && x < intervals[i].to) {
            return i;
        }
    }
    throw new Error('Argument not within intervals');
}

// test:
const testvalues = [5, 21, 90, 345, 878, 9234802];
for (let x of testvalues) {
    console.log(`interval of ${x}: `   findInterval(x));
}

// output:
interval of 5: 0
interval of 21: 1
interval of 90: 2
interval of 345: 3
interval of 878: 4
interval of 9234802: 5

CodePudding user response:

You can try this

const ranges = [
  [0, 20],
  [20, 70],
  [70, 200],
  [200, 500],
  [500, 10000],
  [1000, Infinity]
];

function getIntersectionIndex(x) {
  for (let i = 0; i < ranges.length; i  ) {
    if (ranges[i][0] <= x && x < ranges[i][1])
      return i;
  }
  return -1;
}

const y = getIntersectionIndex(10); // returns 0
  • Related