Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Min and max values based on the given values?

Tags:

javascript

i'll be getting two values bigValue & smallValue based on this I should set maxValue & minValue, below are the conditions explained

if bigValue=42 & smallValue=23 then maxValue=50 & minValue=20

if bigValue=12 & smallValue=03 then maxValue=20 & minValue=0

if bigValue=0.156 & smallValue=0.1 then maxValue=0.2 & minValue=0.1

if bigValue=0.0156 & smallValue=0.01 then maxValue=0.02 & minValue=0.01

How to achieve this with better logic using only javascript?

Here bigValue & smallValue can be of any values & both will be positive.

I have this requirement to set the start and end point for y-axis in graph.

like image 972
SKADIN Avatar asked Mar 14 '23 04:03

SKADIN


2 Answers

This proposal works with the logarithm of 10 for the wanted range. It works for small numbers as well, even with one min/max zero value and negative values.

function getBorders(min, max) {
    var v = Math.pow(10, Math.floor(Math.log(Math.max(Math.abs(min), Math.abs(max))) / Math.log(10)));
    return {
        left: Math.floor(min / v) * v || 0,
        right: Math.ceil(max / v) * v || 0
    };
}

var values = [{ "min": 80, "max": 100 }, { "min": 23, "max": 42 }, { "min": 3, "max": 12 }, { "min": 0.1, "max": 0.156 }, { "min": 0.01, "max": 0.0156 }, { "min": 30, "max": 255 }, { "min": 1255, "max": 2784 }, { "min": 0.0023, "max": 0.00769 }, { "min": 0, "max": 0.002 }, { "min": 0, "max": 15000 }, { "min": -23, "max": 0 }, { "min": -123, "max": 2 }, { "min": 0, "max": 0 }];

values.forEach(function (a) {
    var o = getBorders(a.min, a.max);
    Object.keys(o).forEach(function (k) { a[k] = o[k]; });
});

console.log(values);
like image 122
Nina Scholz Avatar answered Mar 25 '23 00:03

Nina Scholz


If, according to the example cases, your requirement is to set the bigValue to the nearest upper tenth and the smallValue to the nearest lower tenth: the following should work fine for both positive integers and positive decimals.

Using the ternary operator:

//if decimal: get the largest non-zero position
if (bigValue< 1) {
   decBig = Math.ceil(-Math.log10(bigValue));}

if (smallValue< 1) {
   decSmall = Math.ceil(-Math.log10(smallValue))};

maxValue =  bigValue >= 1? Math.ceil(bigValue/10) *10 : Math.ceil(bigValue*Math.pow(10,decBig))/Math.pow(10,decBig);
minValue =  smallValue>= 1? Math.floor(smallValue /10) *10 : Math.floor(smallValue*Math.pow(10,decBig))/Math.pow(10,decBig); 
like image 35
dshgna Avatar answered Mar 24 '23 22:03

dshgna