UNPKG

2.11 kBJavaScriptView Raw
1import { MERGE, ACCUM, INCRE, COUNT } from '@analys/enum-pivot-mode';
2import { Accumulators } from '@analys/util-pivot';
3
4const {
5 merge: merge$1,
6 accum: accum$1
7} = Accumulators;
8const findEntry = function (key) {
9 return this.find(([k]) => key === k);
10};
11const EntriesRecorder = mode => {
12 if (mode === MERGE) return function (x, v) {
13 const en = findEntry.call(this, x);
14
15 if (en) {
16 merge$1(en[1], v);
17 } else {
18 this.push([x, v.slice()]);
19 }
20 };
21 if (mode === ACCUM) return function (x, v) {
22 const en = findEntry.call(this, x);
23
24 if (en) {
25 accum$1(en[1], v);
26 } else {
27 this.push([x, [v]]);
28 }
29 };
30 if (mode === INCRE) return function (x, v) {
31 const en = findEntry.call(this, x);
32
33 if (en) {
34 en[1] += v;
35 } else {
36 this.push([x, v]);
37 }
38 };
39 if (mode === COUNT) return function (x) {
40 const en = findEntry.call(this, x);
41
42 if (en) {
43 en[1]++;
44 } else {
45 this.push([x, 1]);
46 }
47 };
48 return () => {};
49};
50
51const {
52 merge,
53 accum
54} = Accumulators;
55const ObjectRecorder = mode => {
56 if (mode === MERGE) return function (x, v) {
57 if (x in this) {
58 merge(this[x], v);
59 } else {
60 this[x] = v.slice();
61 }
62 };
63 if (mode === ACCUM) return function (x, v) {
64 if (x in this) {
65 accum(this[x], v);
66 } else {
67 this[x] = [v];
68 }
69 };
70 if (mode === INCRE) return function (x, v) {
71 if (x in this) {
72 this[x] += v;
73 } else {
74 this[x] = v;
75 }
76 };
77 if (mode === COUNT) return function (x) {
78 if (x in this) {
79 this[x]++;
80 } else {
81 this[x] = 1;
82 }
83 };
84 return () => {};
85};
86
87function tableChips({
88 key,
89 field,
90 mode = ACCUM,
91 objectify = true
92} = {}) {
93 const {
94 head,
95 rows
96 } = this,
97 l = rows.length;
98 const ki = head.indexOf(key),
99 vi = head.indexOf(field);
100 let chips, row;
101 const note = objectify ? ObjectRecorder(mode).bind(chips = {}) : EntriesRecorder(mode).bind(chips = []);
102
103 for (let i = 0; i < l && (row = rows[i]); i++) note(row[ki], row[vi]);
104
105 return chips;
106}
107
108export { tableChips };