Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a function that determines value between 2 numbers

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?

like image 983
Alon Avatar asked Aug 27 '12 15:08

Alon


People also ask

What is the Excel function for difference between two numbers?

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.

How do you create a range condition in Excel?

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 ".

How do I find the data between two values in Excel?

Excel allows a user to lookup a value between two numbers using the LOOKUP function.


2 Answers

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!");
}
like image 129
Jordão Avatar answered Oct 19 '22 09:10

Jordão


function returnSize(number, sizeMap) {
    for (var key in sizeMap) {
       if (number < sizeMap[key]) return key;
    }
    return key;
}
like image 2
xdazz Avatar answered Oct 19 '22 07:10

xdazz