BarChartNiceScale.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. class BarChartNiceScale {
  2. minPoint: number;
  3. maxPoint: number;
  4. maxTicks = 10;
  5. tickSpacing!: number;
  6. range!: number;
  7. niceMinimum!: number;
  8. niceMaximum!: number;
  9. constructor(min: number, max: number, maxTicks = 10) {
  10. this.minPoint = min;
  11. this.maxPoint = max;
  12. this.maxTicks = maxTicks;
  13. this.calculate();
  14. }
  15. calculate() {
  16. this.range = this.niceNum(this.maxPoint - this.minPoint, false);
  17. this.tickSpacing = this.niceNum(this.range / (this.maxTicks - 1), true);
  18. this.niceMinimum =
  19. Math.floor(this.minPoint / this.tickSpacing) * this.tickSpacing;
  20. this.niceMaximum =
  21. Math.floor(this.maxPoint / this.tickSpacing) * this.tickSpacing;
  22. }
  23. niceNum(localRange: number, round: boolean) {
  24. const exponent = Math.floor(
  25. Math.log10(localRange)
  26. ); /** exponent of localRange */
  27. const fraction =
  28. localRange / 10 ** exponent; /** fractional part of localRange */
  29. let niceFraction; /** nice, rounded fraction */
  30. if (round) {
  31. if (fraction < 1.5) {
  32. niceFraction = 1;
  33. } else if (fraction < 3) {
  34. niceFraction = 2;
  35. } else if (fraction < 7) {
  36. niceFraction = 5;
  37. } else {
  38. niceFraction = 10;
  39. }
  40. } else if (fraction <= 1) {
  41. niceFraction = 1;
  42. } else if (fraction <= 2) {
  43. niceFraction = 2;
  44. } else if (fraction <= 5) {
  45. niceFraction = 5;
  46. } else {
  47. niceFraction = 10;
  48. }
  49. return niceFraction * 10 ** exponent;
  50. }
  51. setMinMaxPoints(localMinPoint: number, localMaxPoint: number) {
  52. this.minPoint = localMinPoint;
  53. this.maxPoint = localMaxPoint;
  54. this.calculate();
  55. }
  56. setMaxTicks(localMaxTicks: number) {
  57. this.maxTicks = localMaxTicks;
  58. this.calculate();
  59. }
  60. }
  61. export default BarChartNiceScale;