export default class NiceScale {
  constructor(min, max, maxTicks = 10) {
    this.min = min
    this.max = max
    this.maxTicks = maxTicks
    this.niceMin = 0
    this.niceMax = 0
    this.tickSpacing = 0
    this.calculate()
  }

  calculate() {
    const range = this.niceNum(this.max - this.min, false)
    const tickSpacing = this.niceNum(range / (this.maxTicks - 1), true)
    this.niceMin = Math.floor(this.min / tickSpacing) * tickSpacing
    this.niceMax = Math.ceil(this.max / tickSpacing) * tickSpacing
    this.tickSpacing = tickSpacing
  }

  niceNum(x, round) {
    // exponent of x
    const exponent = Math.floor(Math.log10(x))
    // fractional part of x
    const fraction = x / Math.pow(10, exponent)
    // nice, rounded fraction
    let niceFraction

    if (round) {
      if (fraction < 1.5) {
        niceFraction = 1
      } else if (fraction < 3) {
        niceFraction = 2
      } else if (fraction < 7) {
        niceFraction = 5
      } else {
        niceFraction = 10
      }
    } else {
      if (fraction <= 1) {
        niceFraction = 1
      } else if (fraction <= 2) {
        niceFraction = 2
      } else if (fraction <= 5) {
        niceFraction = 5
      } else {
        niceFraction = 10
      }
    }

    return niceFraction * Math.pow(10, exponent)
  }
}
