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
}
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
}
Share
Improve this question
asked Sep 25, 2009 at 15:50
DA.DA.
40.7k51 gold badges160 silver badges217 bronze badges
3 Answers
Reset to default 4Here'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);
}
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)
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 ];
}
}