Skip to content

Instantly share code, notes, and snippets.

@rolandcoops
Last active November 16, 2017 18:37
Show Gist options
  • Save rolandcoops/d52e926d327b1cad59e8735dd4493510 to your computer and use it in GitHub Desktop.
Save rolandcoops/d52e926d327b1cad59e8735dd4493510 to your computer and use it in GitHub Desktop.
Calculate ‘nice’ graph domain by rounding up number through a base-10 range. (ES6)
// Round up to nearest base, in base 10. Works for both negative/positive numbers and numbers -1 < n < 1.
// Useful for calculating a sensible/readible graph domain max if you input the max value of your data.
export const roundUpBaseInRange = (n, bases = [1, 2, 4, 5, 6, 8, 10]) => {
// Store the sign, so we can restore it for the result lateron
const sign = Math.sign(n)
// Get modulus (remove sign) for next steps in calculation
const modulus = Math.abs(n)
// Calculate base10 exponent (i.e. amount of digits as float instead of integer)
const exponent = Math.log10(modulus)
// Floor of the exponent gives the amount of digits offset from
// a base10 number with exponent of 1 (i.e. a single digit number).
// NOTE: If exponent is infinite, that means n is either 0 or -0
const offset = Math.floor(isFinite(exponent) ? exponent : 0)
// Cast modulus as single digit number by using digit offset determined above
const base = modulus * Math.pow(10, -offset)
// Find the single-digit base to round up to
const newBase = bases.find((roundTo) => roundTo >= base)
// Restore original digit offset to new base
const result = newBase * Math.pow(10, offset)
// Restore original sign and return result
return sign * result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment