/
index.js
132 lines (111 loc) · 2.71 KB
/
index.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
'use strict';
module.exports = class Query {
src = [];
constructor(src) {
this.src = src;
}
/**
* @returns The underlying array.
*/
all() {
return this.src;
}
/**
* @param key If array of objects you can provides
* a key
* @returns The the average of of the sum of the array.
*/
average(key) {
let sum = this.src.reduce((p, c, i, arr) => {
return key ? p = (i == 1 ? parseInt(arr[0][key]) : parseInt(p)) + parseInt(arr[i][key]) : p = parseInt(p) + parseInt(c);
})
return sum / this.src.length;
}
/**
* @returns The chuncked array based on size provided.
*/
chunck(size) {
let chuncks = [];
let chunck = [];
let c = 1;
let i = 0;
do {
chunck.push(this.src[i]);
if (c == size || i == this.src.length -1) {
chuncks.push(chunck);
chunck = [];
c = 1;
} else {
c++;
}
i++;
} while (i < this.src.length)
return chuncks;
}
combine(keys) {
let results = this.src.map((v, i) => {
let object = {};
object[keys[i]] = v;
return object;
});
return results;
}
concat(arr) {
const result = this.src;
return result.concat(arr);
}
contains(val, explicit) {
return explicit ? this.src.includes(val) : this.src.includes(val.toString()) || this.src.includes(parseInt(val));
}
count() {
return this.src.length;
}
countBy() {
let results = {};
this.src.forEach((v, i) => {
results[v] = results[v] >= 1 ? results[v]+1 : 1;
});
return results;
}
crossJoin(arr) {
let results = [];
this.src.forEach((v, i) => {
arr.forEach((vA, iA) => {
results.push([v, vA]);
})
})
return results;
}
dd() {
// if (window != undefined) {
// let body = document.querySelector('body');
// let dumpContainer = document.createElement('div');
// let dump = document.createTextNode(JSON.stringify(this));
// dumpContainer.appendChild(dump)
// body.appendChild(dumpContainer)
// }
console.log(this);
return this;
}
diff(arr, explicit) {
return this.src.filter((v, i) => {
return explicit ? !arr.includes(parseInt(v)) && !arr.includes(v.toString()) : !arr.includes(v)
})
}
diffObj(arr, key) {
return this.src.filter((v, i) => {
return !arr.includes(v[key])
})
}
/**
* @param key If array of objects you can provides
* a key
* @returns The the average of of the sum of the array.
*/
sum(key) {
let sum = this.src.reduce((p, c, i, arr) => {
return key ? p = (i == 1 ? parseInt(arr[0][key]) : parseInt(p)) + parseInt(arr[i][key]) : p = parseInt(p) + parseInt(c);
})
return sum;
}
};