1 | export default function pretty(min: number, max: number, n: number = 5) {
|
2 |
|
3 | const res = {
|
4 | max: 0,
|
5 | min: 0,
|
6 | ticks: [],
|
7 | };
|
8 |
|
9 | if (min === max) {
|
10 | return {
|
11 | max,
|
12 | min,
|
13 | ticks: [min],
|
14 | };
|
15 | }
|
16 |
|
17 | |
18 |
|
19 |
|
20 |
|
21 |
|
22 | const h = 1.5;
|
23 | const h5 = 0.5 + 1.5 * h;
|
24 |
|
25 | const d = max - min;
|
26 | const c = d / n;
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | const base = Math.pow(10, Math.floor(Math.log10(c)));
|
35 | const toFixed = base < 1 ? Math.ceil(Math.abs(Math.log10(base))) : 0;
|
36 | let unit = base;
|
37 | if (2 * base - c < h * (c - unit)) {
|
38 | unit = 2 * base;
|
39 | if (5 * base - c < h5 * (c - unit)) {
|
40 | unit = 5 * base;
|
41 | if (10 * base - c < h * (c - unit)) {
|
42 | unit = 10 * base;
|
43 | }
|
44 | }
|
45 | }
|
46 | const nu = Math.ceil(max / unit);
|
47 | const ns = Math.floor(min / unit);
|
48 |
|
49 | res.max = Math.max(nu * unit, max);
|
50 | res.min = Math.min(ns * unit, min);
|
51 |
|
52 | let x = Number.parseFloat((ns * unit).toFixed(toFixed));
|
53 | while (x < max) {
|
54 | res.ticks.push(x);
|
55 | x += unit;
|
56 | if (toFixed) {
|
57 | x = Number.parseFloat(x.toFixed(toFixed));
|
58 | }
|
59 | }
|
60 | res.ticks.push(x);
|
61 |
|
62 | return res;
|
63 | }
|