I have a number generator that issues a constant stream of numbers.
For each number, I want to translate that value into the highest threshold it has passed.
For example, the thresholds could be 0, 50, 100, 175, 250, 300, 400, 550.
For the number 55, I would then want to return 50, as that is the highest threshold lower than the value.
Similarly, if the number is 549 I want to return 400.
Etc.
Restrictions: No decimals, no negative numbers.
Also, the values in the threshold list do not follow any meaningful pattern.
Assuming threshold is a list with values sorted in ascending order with the index being L, my current algorithm is something along this:
function findTreshold(value: number) {
switch(true) {
case value >= threshold[L-1]:
return threshold[L-1];
case value >= threshold[L-2]:
return threshold[L-2];
...
default:
return threshold[0];
}
}
The solution needs to run in Javascript (ES6+). The example above is written in Typescript, in case anyone's curious about the switch(true)
syntax.
But I'm curious to see if there's a more effective algorithm around. This function is called continuously so computation time is important.