Home > Enterprise >  How do I find a value in a set of ranges?
How do I find a value in a set of ranges?

Time:12-13

I have a long list of number ranges between 0 and 1000000, each correlating to another number.

It's for an HTML form to calculate prices. I thought about using a set of arrays or an if-else chain, but I'm looking for the most efficient way to accomplish the same task.

Here's a sample:

Range Result
0 - 40000 2000
40001-50000 2500
50001-60000 3000

I'd like to be able to provide the script a number, such as 45000 and have it return 2500 as the result. How can I do this without creating a long if-else chain?

CodePudding user response:

This code will return undefined if no ranges match. The lower end of the range is inclusive, the upper end exclusive.

const ranges = [
  {start:0,     end: 40000, val:2000},
  {start:40000, end: 50000, val:2500},
  {start:50000, end: 60000, val:3000}
]
function f(n) { 
  return ranges.find(({start,end}) => n>=start && n<end)?.val
}
console.log(f(45000))

CodePudding user response:

perhaps looping through objects of that table?

Beloew I've used teh for...of syntax of newer ECMASCript

const values = [
  {lower: 0, upper: 40000, result: 2000},
  {lower: 40001, upper: 50000, result: 2500},
  {lower: 50001, upper: 60000, result: 3000}
]


// ES for...of loop
const getValue = (value) => {
  let result = undefined;
  for (const v of values) {
    if (value >= v.lower && v.upper >= value) {
      result = v.result;
      break;
    }
  }
  return result
}

console.log(getValue(45000))

  • Related