utils.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. const { abs, round, pow } = Math;
  2. export function roundDec(val: number, dec: number) {
  3. return round(val * (dec = 10 ** dec)) / dec;
  4. }
  5. export const fixedDec = new Map();
  6. export function guessDec(num: number) {
  7. return (('' + num).split('.')[1] || '').length;
  8. }
  9. export function genIncrs(base: number, minExp: number, maxExp: number, mults: number[]) {
  10. let incrs = [];
  11. let multDec = mults.map(guessDec);
  12. for (let exp = minExp; exp < maxExp; exp++) {
  13. let expa = abs(exp);
  14. let mag = roundDec(pow(base, exp), expa);
  15. for (let i = 0; i < mults.length; i++) {
  16. let _incr = mults[i] * mag;
  17. let dec = (_incr >= 0 && exp >= 0 ? 0 : expa) + (exp >= multDec[i] ? 0 : multDec[i]);
  18. let incr = roundDec(_incr, dec);
  19. incrs.push(incr);
  20. fixedDec.set(incr, dec);
  21. }
  22. }
  23. return incrs;
  24. }
  25. const onlyWhole = (v: number) => v % 1 === 0;
  26. const allMults = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5];
  27. // ...0.01, 0.02, 0.025, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.2, 0.25, 0.3, 0.4, 0.5...
  28. export const decIncrs = genIncrs(10, -16, 0, allMults);
  29. // 1, 2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 20, 25, 30, 40, 50...
  30. export const oneIncrs = genIncrs(10, 0, 16, allMults);
  31. // 1, 2, 3, 4, 5, 10, 20, 25, 50...
  32. export const wholeIncrs = oneIncrs.filter(onlyWhole);
  33. export const numIncrs = decIncrs.concat(oneIncrs);
  34. export const niceLinearIncrs = decIncrs.concat(wholeIncrs);
  35. const sec = 1 * 1e3;
  36. const min = 60 * sec;
  37. const hour = 60 * min;
  38. const day = 24 * hour;
  39. const year = 365 * day;
  40. // in milliseconds
  41. export const niceTimeIncrs = [
  42. 1,
  43. 2,
  44. 4,
  45. 5,
  46. 10,
  47. 20,
  48. 25,
  49. 40,
  50. 50,
  51. 100,
  52. 200,
  53. 250,
  54. 400,
  55. 500,
  56. sec,
  57. 2 * sec,
  58. 4 * sec,
  59. 5 * sec,
  60. 10 * sec,
  61. 15 * sec,
  62. 20 * sec,
  63. 30 * sec,
  64. min,
  65. 2 * min,
  66. 4 * min,
  67. 5 * min,
  68. 10 * min,
  69. 15 * min,
  70. 20 * min,
  71. 30 * min,
  72. hour,
  73. 2 * hour,
  74. 4 * hour,
  75. 6 * hour,
  76. 8 * hour,
  77. 12 * hour,
  78. 18 * hour,
  79. day,
  80. 2 * day,
  81. 3 * day,
  82. 4 * day,
  83. 5 * day,
  84. 6 * day,
  85. 7 * day,
  86. 10 * day,
  87. 15 * day,
  88. 30 * day,
  89. 45 * day,
  90. 60 * day,
  91. 90 * day,
  92. 180 * day,
  93. year,
  94. 2 * year,
  95. 3 * year,
  96. 4 * year,
  97. 5 * year,
  98. 6 * year,
  99. 7 * year,
  100. 8 * year,
  101. 9 * year,
  102. 10 * year,
  103. ];