UNPKG

1.85 kBPlain TextView Raw
1import { each, head, last } from '@antv/util';
2import Continuous from './base';
3
4/**
5 * 分段度量
6 */
7class Quantize extends Continuous {
8 public type = 'quantize';
9
10 public invert(value): number {
11 const ticks = this.ticks;
12 const length = ticks.length;
13 const percent = this.getInvertPercent(value);
14 const minIndex = Math.floor(percent * (length - 1));
15 // 最后一个
16 if (minIndex >= length - 1) {
17 return last(ticks);
18 }
19 // 超出左边界, 则取第一个
20 if (minIndex < 0) {
21 return head(ticks);
22 }
23 const minTick = ticks[minIndex];
24 const nextTick = ticks[minIndex + 1];
25 // 比当前值小的 tick 在度量上的占比
26 const minIndexPercent = minIndex / (length - 1);
27 const maxIndexPercent = (minIndex + 1) / (length - 1);
28 return minTick + (percent - minIndexPercent) / (maxIndexPercent - minIndexPercent) * (nextTick - minTick);
29 }
30
31 protected initCfg() {
32 this.tickMethod = 'r-pretty';
33 this.tickCount = 5;
34 this.nice = true;
35 }
36
37 protected calculateTicks(): any[] {
38 const ticks = super.calculateTicks();
39 if (!this.nice) { // 如果 nice = false ,补充 min, max
40 if (last(ticks) !== this.max) {
41 ticks.push(this.max);
42 }
43 if (head(ticks) !== this.min) {
44 ticks.unshift(this.min);
45 }
46 }
47 return ticks;
48 }
49
50 // 计算当前值在刻度中的占比
51 protected getScalePercent(value) {
52 const ticks = this.ticks;
53 // 超出左边界
54 if (value < head(ticks)) {
55 return 0;
56 }
57 // 超出右边界
58 if (value > last(ticks)) {
59 return 1;
60 }
61 let minIndex = 0;
62 each(ticks, (tick, index) => {
63 if (value >= tick) {
64 minIndex = index;
65 } else {
66 return false;
67 }
68 });
69 return minIndex / (ticks.length - 1);
70 }
71}
72
73export default Quantize;