-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupedArray.ts
More file actions
64 lines (52 loc) · 1.8 KB
/
GroupedArray.ts
File metadata and controls
64 lines (52 loc) · 1.8 KB
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
/// <reference path="MultiKeyDictionary" />
/// <reference path="OrderedSet" />
class GroupedArray<T> extends Array<T>{
private groupedValues: MultiKeyDictionary<T>;
private groupDimensions: Array<OrderedSet>;
protected groupers: Array<(arg:T)=>any>;
constructor(array: Array<T>, groupers: Array<(arg:T)=>any> = []){
this.groupDimensions = [];
this.groupedValues = new MultiKeyDictionary<T>();
super(array.length);
array.forEach((el) => this.push(el));
this.groupers = groupers;
}
groupByFunction(grouper:(arg:T)=>any) {
this.groupers.push(grouper);
}
aggregate(fun:(arr:Array<T>)=>any) {
this.performGrouping();
let recursiveAggregate =
(lockedKeys:Array<any>, lockedIndices:Array<Number>) => {
if (lockedKeys.length == this.groupDimensions.length) {
return fun.call(
{},
this.groupedValues.get(lockedKeys),
lockedKeys,
lockedIndices
);
}
return this.groupDimensions[lockedKeys.length].map(
(groupKey, i) => {
var nextKeys = lockedKeys.slice();
nextKeys.push(groupKey);
var nextIndices = lockedIndices.slice(); nextIndices.push(i);
return recursiveAggregate(nextKeys, nextIndices);
}
);
}
return recursiveAggregate([],[]);
}
private performGrouping () :void {
this.groupDimensions = this.groupers.map( () => new OrderedSet );
this.forEach((value) => {
let keys:Array<any> = this.groupers.map(
(grouper) => grouper(value)
);
this.groupedValues.add(keys, value);
keys.forEach((key,index) => {
this.groupDimensions[index].insert(key);
})
});
}
}