-
Notifications
You must be signed in to change notification settings - Fork 188
/
Copy pathticks.js
55 lines (51 loc) · 1.91 KB
/
ticks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const e10 = Math.sqrt(50),
e5 = Math.sqrt(10),
e2 = Math.sqrt(2);
function tickSpec(start, stop, count) {
const step = (stop - start) / Math.max(0, count),
power = Math.floor(Math.log10(step)),
error = step / Math.pow(10, power),
factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1;
let i1, i2, inc;
if (power < 0) {
inc = Math.pow(10, -power) / factor;
i1 = Math.round(start * inc);
i2 = Math.round(stop * inc);
if (i1 / inc < start) ++i1;
if (i2 / inc > stop) --i2;
inc = -inc;
} else {
inc = Math.pow(10, power) * factor;
i1 = Math.round(start / inc);
i2 = Math.round(stop / inc);
if (i1 * inc < start) ++i1;
if (i2 * inc > stop) --i2;
}
if (i2 < i1 && 0.5 <= count && count < 2) return tickSpec(start, stop, count * 2);
return [i1, i2, inc];
}
export default function ticks(start, stop, count) {
stop = +stop, start = +start, count = +count;
if (!(count > 0)) return [];
if (start === stop) return [start];
const reverse = stop < start, [i1, i2, inc] = reverse ? tickSpec(stop, start, count) : tickSpec(start, stop, count);
if (!(i2 >= i1)) return [];
const n = i2 - i1 + 1, ticks = new Array(n);
if (reverse) {
if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) / -inc;
else for (let i = 0; i < n; ++i) ticks[i] = (i2 - i) * inc;
} else {
if (inc < 0) for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) / -inc;
else for (let i = 0; i < n; ++i) ticks[i] = (i1 + i) * inc;
}
return ticks;
}
export function tickIncrement(start, stop, count) {
stop = +stop, start = +start, count = +count;
return tickSpec(start, stop, count)[2];
}
export function tickStep(start, stop, count) {
stop = +stop, start = +start, count = +count;
const reverse = stop < start, inc = reverse ? tickIncrement(stop, start, count) : tickIncrement(start, stop, count);
return (reverse ? -1 : 1) * (inc < 0 ? 1 / -inc : inc);
}