-
Notifications
You must be signed in to change notification settings - Fork 0
/
groupcreator.js
99 lines (90 loc) · 2.73 KB
/
groupcreator.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
function createGroupJob (lib, mylib) {
'use strict';
var qlib = lib.qlib;
var SteppedJobOnSteppedInstance = qlib.SteppedJobOnSteppedInstance;
function GroupJobCore (options) {
this.options = options;
this.finalResult = void 0;
this.resultMap = new lib.Map();
}
GroupJobCore.prototype.destroy = function () {
if(this.resultMap) {
this.resultMap.destroy();
}
this.resultMap = null;
this.finalResult = null;
this.options = null;
};
GroupJobCore.prototype.shouldContinue = function () {
if (lib.defined(this.finalResult)) {
return this.finalResult;
}
if(!this.options) {
throw new lib.Error('NO_OPTIONS', this.constructor.name+' needs to have options');
}
if (!lib.isArray(this.options.data)) {
throw new lib.Error('NO_OPTIONS.DATA', this.constructor.name+' needs to have options.data');
}
if (!this.options.group) {
throw new lib.Error('NO_OPTIONS.GROUP', this.constructor.name+' needs to have options.group');
}
if (!this.options.group.by) {
throw new lib.Error('NO_OPTIONS.GROUP.BY', this.constructor.name+' needs to have options.group.by');
}
};
GroupJobCore.prototype.init = function () {
return mylib.traverse({
data: this.options.data,
filter: this.options.filter,
cb: this.grouper.bind(this)
});
};
GroupJobCore.prototype.finalize = function () {
var ret = [], _r = ret, gb = this.options.group.by;
this.resultMap.traverse(finalizer.bind(null, _r, gb));
_r = null;
gb = null;
return ret;
};
function finalizer (ret, gb, val, name) {
val[gb] = name;
ret.push(val);
}
GroupJobCore.prototype.steps = [
'init',
'finalize'
];
GroupJobCore.prototype.grouper = function (rec) {
var found = true;
var val = lib.readPropertyFromDotDelimitedString(rec, this.options.group.by);
var mapitem = this.resultMap.get(val);
if (!mapitem) {
found = false;
mapitem = {};
mapitem[this.options.group.by] = null;
}
lib.traverseShallow(this.options.group.fields, subgrouper.bind(null, mapitem, rec));
if (!found) {
this.resultMap.add(val, mapitem);
}
mapitem = null;
rec = null;
};
function subgrouper (mapitem, rec, op, field) {
var agg = mylib.aggregatorFactory(op);
mapitem[field] = agg(mapitem[field], lib.readPropertyFromDotDelimitedString(rec, field));
}
function GroupJob (options, defer) {
SteppedJobOnSteppedInstance.call(
this,
new GroupJobCore(options),
defer
)
}
lib.inherit(GroupJob, SteppedJobOnSteppedInstance);
mylib.jobs.Group = GroupJob;
mylib.group = function (options, defer) {
return (new GroupJob(options, defer)).go();
}
}
module.exports = createGroupJob;