DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Pretty Gridline Creation

07.08.2008
| 1938 views |
  • submit to reddit
        
private function DetermineGridSteps(min, max, num_steps) {
    num_steps = num_steps || 5;
    var rough_step = (max - min) / num_steps;
    var exponent = Math.floor(Math.log(Math.abs(rough_step)) / Math.LN10); 
    if (rough_step == 0) exponent = 0;
    
    var tenToPower = Math.pow(10, exponent);
    var mantissa = rough_step / tenToPower;
    var step = Math.ceil(mantissa) * tenToPower;

    var steps = Array();
    steps.push(min);
    
    var next_step = (Math.ceil(min/step) * step);
    if (next_step <= min) next_step += step;
    while(next_step < max) {
        steps.push(next_step);
        next_step += step;
    }
    steps.push(max);
}

0 --> 10
0__2__4__6__8__10
 
1 --> 10
1__2__4__6__8__10
 
0 --> 50
0__10__20__30__40__50
 
1 --> 499
1__100__200__300__400__499
 
0 --> 1.7
0__0.4__0.8__1.2__1.6__1.7
 
1 --> 49999
1__10000__20000__30000__40000__49999
 
361 --> 413
361__380__400__413