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?
Calculate the difference between two numbers by inputting a formula in a new, blank cell. If A1 and B1 are both numeric values, you can use the "=A1-B1" formula. Your cells don't have to be in the same order as your formula. For example, you can also use the "=B1-A1" formula to calculate a different value.
To enter a range to use as a criterion, type *, enter the range reference normally, then after the range reference but before the right parenthesis, type =", then the value to match, then ".
Excel allows a user to lookup a value between two numbers using the LOOKUP function.
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!");
}
function returnSize(number, sizeMap) {
for (var key in sizeMap) {
if (number < sizeMap[key]) return key;
}
return key;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With