How to create a function that determines value between 2 numbers
javascript, object
Solution
To have a deterministic output, I'd prefer to have an array ordered by the categories in question:
var categories = [
{label: 'small', upTo: 25},
{label: 'medium', upTo: 80},
{label: 'large', upTo: 150} ];
(you can even create this array from your original `sizeMap`)
And then you can do:
function getSizeCategory(number, categories) {
for (var i = 0; i < categories.length; ++i) {
if (number < categories[i].upTo) {
return categories[i].label;
}
}
throw new Error("not in range!");
}
Problem
I have this range of numbers: ``` 0 -------> 25 -------> 80 ------> 150 small medium large ``` I want to recieve a number between 0 to 150 and to display whether it is small, medium or big. 30 and 45 are medium because they are between 25 and 80 and 5 is small because it is lower than 25. I want to create a function that does this matching for this object: ``` var sizeMap = { small : 25, medium : 80, large : 150 } ``` (assuming that 0 is the lowest number). The function should look like: ``` function returnSize(number) { for (item in sizeMap) ??????? return size } ``` how do I write this function so it can be flexible for adding new categories (for example: 'extra large' : 250). Should I present the object as an array?