views:

64

answers:

3

I have a bit of javascript that I am using to calculate the y-scale of a graph. I need to adjust the scale according to the value. This works but seems really verbose. Is there a more streamlined way to do this?

if (maxValue <= 20000){
 chartMaxY = 20000
}  
if (maxValue <= 10000){
 chartMaxY = 10000
}  
if (maxValue <= 5000){
 chartMaxY = 5000
}  
if (maxValue <= 2500){
 chartMaxY = 2500
}
if (maxValue <= 1000){
 chartMaxY = 1000
}
if (maxValue <= 500){
 chartMaxY = 500
}  
if (maxValue <= 250){
 chartMaxY = 250
}   
if (maxValue <= 100){
 chartMaxY = 100
} 
if (maxValue <= 50){
 chartMaxY = 50
} 
if (maxValue <= 10){
 chartMaxY = 10
}
+2  A: 

Why not use a for loop?

var vals = [ 20000, 10000, 5000, 2500, 1000, 500, 250, 100, 50, 10 ];

for( var i = 0; i < vals.length; i++ )
{
    if( maxValue >  vals[ i ] )
    {
        break;
    }
    else
    {
        chartMaxY = vals[ i ];
    }
}
Christopher W. Allen-Poole
Thanks, Chris! I appreciate it.
DA
+3  A: 

Same thing, possibly more succinct depending on your programming style.

var keys = [10, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 20000];

for (var i=0; i<keys.length; i++) {
    if (maxValue <= keys[i]) {
        chartMaxY = keys[i];
        break;
    }
}

The reverse order of key-values causes maxValue to only be set once, but note this does not modify values > 20000 (though neither did original)

Chadwick
Yours is definitely a better algorithm than mine.
Christopher W. Allen-Poole
Thanks, Chadwick. I learned something!
DA
+4  A: 

Here's a solution without a loop that will scale to 1, 2.5, 5, 10, 2.5, ... for arbitrarily large values:

function maxScale(x) {
    var l = Math.log(x) / Math.LN10, p = Math.floor(l), q = Math.pow(10, l - p);
    return Math.pow(10, p) * (q > 2.5 ? (q > 5 ? 10 : 5) : 2.5);
}
Uh Clem
4 lines is definitely more succinct than mine. Thanks!
DA
+1 for an algorithmic solution, as opposed to hard coded values.
Chadwick