UNPKG

1.55 kBPlain TextView Raw
1export 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 R pretty:
19 https://svn.r-project.org/R/trunk/src/appl/pretty.c
20 https://www.rdocumentation.org/packages/base/versions/3.5.2/topics/pretty
21 */
22 const h = 1.5; // high.u.bias
23 const h5 = 0.5 + 1.5 * h; // u5.bias
24 // 反正我也不会调参,跳过所有判断步骤
25 const d = max - min;
26 const c = d / n;
27 // 当d非常小的时候触发,但似乎没什么用
28 // const min_n = Math.floor(n / 3);
29 // const shrink_sml = Math.pow(2, 5);
30 // if (Math.log10(d) < -2) {
31 // c = (_.max([ Math.abs(max), Math.abs(min) ]) * shrink_sml) / min_n;
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}