You could fully populate an array sp you can dp a direct index into the array at run-time. Once the original data structure is created, that will be fast at run-time, but not very storage efficient. I generally wouldn't recommend this, but to build the array:
var ranges = [
{min: 0, max: 400, value: 'dog'},
{min: 401, max: 1000, value: 'cat'},
{min: 1001, max: 1233, value: 'rat'}
];
var lookupArray = [];
for (var i = 0; i < ranges.length; i++) {
// make sure array is big enough
lookupArray.length = Math.max(lookupArray.length, ranges[i].max);
for (var j = ranges[i].min, j <= ranges[i].max; j++) {
lookupArray[j] = ranges[i].value;
}
}
// function to find the value for a given index
function findValue(index) {
return(lookupArray[index]);
}
Or, in a more compact structure, you can use a data structure and function like this:
var ranges = [
{min: 0, max: 400, value: 'dog'},
{min: 401, max: 1000, value: 'cat'},
{min: 1001, max: 1233, value: 'rat'}
];
function findValue(index) {
var range;
for (var i = 0; i < ranges.length; i++) {
range = ranges[i];
if (index >= range.min && index <= range.max) {
return(range.value);
}
}
}
alert(findValue(402)); // 'cat'
You could also use a straight array with implicit positions in the array (code and data are a little more compact, but both are a bit less readable):
var ranges = [
0, 400, 'dog',
401, 1000, 'cat',
1001, 1233, 'rat'
];
function findValue(index) {
for (var i = 0; i < ranges.length; i+=3) {
if (index >= ranges[i] && index <= ranges[i+1]) {
return(ranges[i+2];
}
}
}