UNPKG

1.72 kBPlain TextView Raw
1import { indexOf, isNil, isNumber } from '@antv/util';
2import Base from '../base';
3
4/**
5 * 分类度量
6 * @class
7 */
8class Category extends Base {
9 public readonly type: string = 'cat';
10 public readonly isCategory: boolean = true;
11
12 public translate(value: any): number {
13 const index = indexOf(this.values, value);
14 if (index === -1) {
15 return isNumber(value) ? value : NaN;
16 }
17 return index;
18 }
19
20 public scale(value: any): number {
21 const order = this.translate(value);
22 // 分类数据允许 0.5 范围内调整
23 // if (order < this.min - 0.5 || order > this.max + 0.5) {
24 // return NaN;
25 // }
26 const percent = this.calcPercent(order, this.min, this.max);
27 return this.calcValue(percent, this.rangeMin(), this.rangeMax());
28 }
29
30 public invert(scaledValue: number) {
31 const domainRange = this.max - this.min;
32 const percent = this.calcPercent(scaledValue, this.rangeMin(), this.rangeMax());
33 const idx = Math.round(domainRange * percent) + this.min;
34 if (idx < this.min || idx > this.max) {
35 return NaN;
36 }
37 return this.values[idx];
38 }
39
40 public getText(value: any, ...args: any[]): string {
41 let v = value;
42 // value为index
43 if (isNumber(value) && !this.values.includes(value)) {
44 v = this.values[v];
45 }
46 return super.getText(v, ...args);
47 }
48 // 复写属性
49 protected initCfg() {
50 this.tickMethod = 'cat';
51 }
52 // 设置 min, max
53 protected setDomain() {
54 // 用户有可能设置 min
55 if (isNil(this.getConfig('min'))) {
56 this.min = 0;
57 }
58 if (isNil(this.getConfig('max'))) {
59 const size = this.values.length;
60 this.max = size > 1 ? size - 1 : size;
61 }
62 }
63}
64
65export default Category;