# html – Calculate Price Range in Javascript-ThrowExceptions

Exception or error:

How I should approach the JavaScript (can’t use jQuery) to change a price using these range calculations:

I found this js fiddle but it uses jQuery . It is very similar to what I want to achieve although I didn’t see a range code in it, just values .

ie: `your price : 200 so multiple by 0.23` refer to chart. So if I have the price `200` I want to get the value `0.23`.

Is there an easier way, then doing the following code below?

``````  if (maxValue <= 100) {
minvalue = 250
}

if (maxValue <= 250) {
chartMaxY = 500
...
``````

Or declaring values?

``````   var pricerange = [100, 250,, 1000, 2500, 50000, ];

if (maxValue <= pricerange[i]) {
minvalue = pricerange[i];
``````
How to solve:

You can use two arrays, one will be the range and the other what value you should get. For example:

``````var value = 1100; // is between 1000-2500 so we should get 0.20
var chartValue;

var priceRange = [ 100, 250, 1000, 2500, 5000 ];
var priceValue = [ 0.23, 0.12, 0.20, 0.19, 0.19 ];

for(range in priceRange)
if (value >= priceRange[range])
chartValue = priceValue[range];

This works because a new value is assigned when a higher range is detected. For example what happens in the example above is like so: It’s higher than 100 set chartValue to `0.23`, it’s higher than `250` set chartValue to `0.12`, it’s higher than `1000` set chartValue to `0.20`. But it’s not greater than `2500` so that will be the last time it changes. Notice that how this is setup we used only one `greater-than` comparison, and re-setting the value makes the ranges we want.

###

I would likely write two functions with all hard-coded values.

``````function fiveYear (price) {
if (price < 100) {
throw new Erorr('price must be at least 100')
} else if (price > 100 && price < 250) {
return 0.23

// .. etc ..
}
``````

If the values will change often, you’ll need to come up with a more general solution, like putting the values in a database.