Created
July 18, 2012 15:06
-
-
Save millermedeiros/3136745 to your computer and use it in GitHub Desktop.
find closest number in the sequence (1, 5, 10, 50, 100, 500, 1000, ...) that generates less than "n" steps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// find closest number in the sequence (1, 5, 10, 50, 100, 500, 1000, ...) | |
// that generates less than "n" steps | |
// --- | |
// useful for subdividing charts and any other things that requires a scale | |
// that follows reasonable numbers | |
// | |
function getStepSize(val, maxNSteps) { | |
var nSteps; | |
var stepSize = 1; | |
var count = 0; | |
do { | |
if (count) { | |
stepSize *= (count % 2)? 5 : 2; | |
} | |
nSteps = Math.ceil(val / stepSize); | |
count += 1; | |
} while (nSteps > maxNSteps); | |
return stepSize; | |
} | |
// example | |
// ------- | |
getStepSize(1000, 2); // 500 | |
getStepSize(1000, 5); // 500 | |
getStepSize(1000, 10); // 100 | |
getStepSize(1000, 20); // 50 | |
getStepSize(1000, 50); // 50 | |
getStepSize(1000, 150); // 10 |
I was looking for something like this a while back and couldn't find anything because I had no idea what terms to search. Given two bounds, the minimum and maximum values that need to be plotted, I wanted to get a reasonable list of round numbers on which to place the gridlines. After much trial and error I came up with a sloppy but serviceable function and called it "gridlines." https://gist.github.com/3137681
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I needed this feature a couple times but never found a good name for it or saw any other implementation... Any help with the name? That's the only reason why this method it isn't inside the amd-utils/math package.