UNPKG

2.9 kBJavaScriptView Raw
1const each = require('@antv/util/lib/each');
2const maxBy = require('@antv/util/lib/math/maxBy');
3const isArray = require('@antv/util/lib/type/isArray');
4const ArrayUtil = {
5 merge: require('@antv/util/lib/array/merge'),
6 values: require('@antv/util/lib/array/values')
7};
8const Adjust = require('./base');
9
10class Symmetric extends Adjust {
11
12 _initDefaultCfg() {
13 this.xField = null; // 调整对应的 x 方向对应的字段名称
14 this.yField = null; // 调整对应的 y 方向对应的字段名称
15 this.cacheMax = null; // 缓存的最大值
16 this.adjustNames = [ 'y' ]; // Only support stack y
17 this.groupFields = null; // 参与分组的数据维度
18 }
19
20 // 获取最大的y值
21 _getMax(dim) {
22 const self = this;
23 const mergeData = self.mergeData;
24 const maxRecord = maxBy(mergeData, obj => {
25 const value = obj[dim];
26 if (isArray(value)) {
27 return Math.max.apply(null, value);
28 }
29 return value;
30 });
31 const maxValue = maxRecord[dim];
32 const max = isArray(maxValue) ? Math.max.apply(null, maxValue) : maxValue;
33 return max;
34 }
35
36 // 获取每个字段最大的值
37 _getXValuesMax() {
38 const self = this;
39 const yField = self.yField;
40 const xField = self.xField;
41 const cache = {};
42 const mergeData = self.mergeData;
43 each(mergeData, function(obj) {
44 const xValue = obj[xField];
45 const yValue = obj[yField];
46 const max = isArray(yValue) ? Math.max.apply(null, yValue) : yValue;
47 cache[xValue] = cache[xValue] || 0;
48 if (cache[xValue] < max) {
49 cache[xValue] = max;
50 }
51 });
52 return cache;
53 }
54
55 // 入口函数
56 processAdjust(dataArray) {
57 const self = this;
58 const mergeData = ArrayUtil.merge(dataArray);
59 self.mergeData = mergeData;
60 self._processSymmetric(dataArray);
61 self.mergeData = null;
62 }
63
64 // 处理对称
65 _processSymmetric(dataArray) {
66 const self = this;
67 const xField = self.xField;
68 const yField = self.yField;
69 const max = self._getMax(yField);
70 const first = dataArray[0][0];
71
72 let cache;
73 if (first && isArray(first[yField])) {
74 cache = self._getXValuesMax();
75 }
76 each(dataArray, function(data) {
77 each(data, function(obj) {
78 const value = obj[yField];
79 let offset;
80 if (isArray(value)) {
81 const xValue = obj[xField];
82 const valueMax = cache[xValue];
83 offset = (max - valueMax) / 2;
84 const tmp = [];
85 /* eslint-disable no-loop-func */
86 each(value, function(subVal) { // 多个字段
87 tmp.push(offset + subVal);
88 });
89 /* eslint-enable no-loop-func */
90 obj[yField] = tmp;
91 } else {
92 offset = (max - value) / 2;
93 obj[yField] = [ offset, value + offset ];
94 }
95 });
96 });
97 }
98}
99
100Adjust.Symmetric = Symmetric;
101module.exports = Symmetric;