-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
556 lines (474 loc) · 14.8 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
const { parseJson, getByProperty, compare } = require('./Helpers');
const QueryManager = require('./QueryManager');
class JSJsonQ {
/**
* constructor - A JSJsonQ Object can be initialized with a filepath{type: string}
* or a Json String{type: string} or a Json Object {type: Object}
*
* @param {string|Object} json required
*
* @returns
* @throws {Error}
*/
constructor(json) {
if (!json) {
throw Error(
'You must pass a filePath or a Json Object or a Json String as parameter'
);
}
this._baseContent = parseJson(json);
this._queryManager = new QueryManager();
this.reset();
}
/**
* reset - A JsonQuery Object can be reset to new data according to the
* given filepath{type: string} or a Json String{type: string}
* or a Json Object {type: Object}.
* The method parameter 'data' is optional. If no 'data' given,
* the JsonQuery Object will be reset to the previously initialized data.
* All the query and processing done so far will be reset to initial state too.
*
* @param {string|Object} data optional
*
* @returns {JsonQuery} Object reference
*/
reset(data) {
data = parseJson(data || this._baseContent);
if (Array.isArray(data)) {
this._jsonContent = Array.from(data);
} else {
this._jsonContent = JSON.parse(JSON.stringify(data));
}
this._queryManager.reset();
return this;
}
/**
* copy - Clone and return the exact same copy of the this Object instance
*
* @returns {JsonQuery}
*/
copy() {
return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
}
/**
* _prepare - Pseudo private method to process data based on the queries
*
* @returns {None}
*/
_prepare() {
this._jsonContent = this._queryManager.prepare(this._jsonContent);
}
/**
* fetch - get the processed data after executing queries
*
* @returns {mixed}
*/
fetch() {
this._prepare();
return this._jsonContent;
}
/**
* chunk - group the resulted collection to multiple chunk
*
* @param {integer} The length of each chunk
* @param {fn} an anonymous function
* @return {Array} New Array
*/
chunk(size = 0, fn = null) {
if(size <= 0) {
throw Error('Invalid chunk size');
}
this._prepare();
let _newContent = [];
while(this._jsonContent.count() > 0) {
_newContent.push(this._jsonContent.splice(0, size));
}
if(fn instanceof Function) {
for(let i = 0; i < this._jsonContent.length; i++) {
_newContent[i] = fn(_newContent[i]);
}
}
this._jsonContent = _newContent;
return this._jsonContent;
}
/**
* at - get the data traversing through the given path hierarchy
* Will return the JsonQuery Object instance, so that further
* Query can be done on that data
*
* @param {string} path path hierarchy as a string, separated by '.'
*
* @returns {JsonQuery} Object reference
*/
at(path) {
const keyParts = path
.trim()
.split('.')
.filter(val => val != '');
for (const key of keyParts) {
this._jsonContent = getByProperty(key, this._jsonContent);
}
return this;
}
/**
* from - Alias method of at()
*
* @param {type} path Description
*
* @returns {type} Description
*/
from(path) {
return this.at(path);
}
/* ------------------------- Query Methods ------------------------- */
/**
* find - get the data traversing through the given path hierarchy
* works like at() method, except it will return the processed data.
* So, no further query method can be chained on it.
*
* @param {type} path Description
*
* @returns {mixed} Description
* @throws {Error}
*/
find(path) {
if (!path) {
throw Error('Invalid parameter given');
}
return this.at(path).fetch();
}
/**
* where - This method is avaialble to run different types of Query on data,
* such as if the given key is equal to, not equal to, greater than, less than
* etc.
* Details can be found at Example.
*
* @param {string} key 'key' to be searched for
* @param {string} op operator (valid operator lists are defined in Matcher Class)
* @param {mixed|Function} val can be a data or an anonymous function
*
* @returns {JsonQuery} Object instance
*/
where(key, op, val) {
if (key instanceof Function) {
key(this);
} else {
this._queryManager.insertQuery({ key, op, val });
}
return this;
}
/**
* orWhere - This method is avaialble to run different types of Query on data,
* such as if the given key is equal to, not equal to, greater than, less than
* etc. These queries will be ORed with other queries.
* Details can be found at Example.
*
* @param {string} key 'key' to be searched for
* @param {string} op operator (valid operator lists are defined in Matcher Class)
* @param {mixed|Function} val can be a data or an anonymous function
*
* @returns {JsonQuery} Object instance
*/
orWhere(key, op, val = null) {
// For a 'Or' type query, every time a new Query group will be created
this._queryManager.createQueryGroup();
if (key instanceof Function) {
key(this);
} else {
this._queryManager.insertQuery({ key, op, val });
}
return this;
}
/**
* whereIn - alias for method call: where(key, 'in', array)
*
* @param {string} key 'key' to be searched for
* @param {mixed|Function} val can be a data or an anonymous function
*
* @returns {JsonQuery} Object instance
*/
whereIn(key, val) {
return this.where(key, 'in', val);
}
/**
* whereNotIn - alias for method call: where(key, 'notin', array)
*
* @param {string} key 'key' to be searched for
* @param {mixed|Function} val can be a data or an anonymous function
*
* @returns {JsonQuery} Object instance
*/
whereNotIn(key, val) {
return this.where(key, 'notin', val);
}
/**
* whereNull - alias for method call: where(key, 'null')
*
* @param {string} key 'key' to be searched for
*
* @returns {JsonQuery} Object instance
*/
whereNull(key) {
return this.where(key, 'null');
}
/**
* whereNotNull - alias for method call: where(key, 'notnull')
*
* @param {string} key 'key' to be searched for
*
* @returns {JsonQuery} Object instance
*/
whereNotNull(key) {
return this.where(key, 'notnull');
}
/**
* whereStartsWith - alias for method call: where(key, 'startswith', val)
*
* @param {string} key 'key' to be searched for
* @param {mixed|Function} val can be a data or an anonymous function
*
* @returns {JsonQuery} Object instance
*/
whereStartsWith(key, val) {
return this.where(key, 'startswith', val);
}
/**
* whereEndsWith - alias for method call: where(key, 'endswith', val)
*
* @param {string} key 'key' to be searched for
* @param {mixed|Function} val can be a data or an anonymous function
*
* @returns {JsonQuery} Object instance
*/
whereEndsWith(key, val) {
return this.where(key, 'endswith', val);
}
/**
* whereContains - alias for method call: where(key, 'contains', val)
*
* @param {string} key 'key' to be searched for
* @param {mixed|Function} val can be a data or an anonymous function
*
* @returns {JsonQuery} Object instance
*/
whereContains(key, val) {
return this.where(key, 'contains', val);
}
/* --------------------- Aggregate Methods ------------------------- */
/**
* sum - If a 'property' given as parameter this method will return the summation
* result of the collection contains that property, otherwise it will assume
* that the collection is an integer array and just return sum of all of them
*
* @param {string} property
*
* @returns {int|float}
*/
sum(property) {
this._prepare();
return this._jsonContent.reduce(
(acc, current) =>
Number(acc) + Number(property ? current[property] : current),
0
);
}
/**
* count - returns the size of the collection
*
* @returns {int}
*/
count() {
this._prepare();
return this._jsonContent.length;
}
/**
* size - returns the size of the collection
*
* @returns {int}
*/
size() {
return this.count();
}
/**
* max - If a 'property' given as parameter this method will return the maximum
* value of the collection contains that property, otherwise it will assume
* that the collection is an integer array and just return maximum of them
*
* @param {string} property
*
* @returns {int|float}
*/
max(property) {
this._prepare();
return this._jsonContent.reduce((max, current) => {
const elem = property ? current[property] : current;
return max > elem ? max : elem;
}, property ? this._jsonContent[0][property] : this._jsonContent[0]);
}
/**
* min - If a 'property' given as parameter this method will return the minimum
* value of the collection contains that property, otherwise it will assume
* that the collection is an integer array and just return minimum of them
*
* @param {string} property
*
* @returns {int|float}
*/
min(property) {
this._prepare();
return this._jsonContent.reduce((min, current) => {
const elem = property ? current[property] : current;
return min < elem ? min : elem;
}, property ? this._jsonContent[0][property] : this._jsonContent[0]);
}
/**
* avg - returns the average of the result by summing up the values of
* given property divided by their count
*
* @returns {int|float}
*/
avg(property) {
this._prepare();
return this.sum(property) / this.count();
}
/**
* first - Returns the first element of the collection
*
* @returns {mixed}
*/
first() {
this._prepare();
return this.count() > 0 ? this._jsonContent[0] : null;
}
/**
* last - Returns the last element of the collection
*
* @returns {mixed}
*/
last() {
this._prepare();
return this.count() > 0 ? this._jsonContent[this.count() - 1] : null;
}
/**
* nth - Returns the nth element of the collection by the given index (n)
* if the given index is negative, such as -2, it will return the value of
* nth index from the end.
*
* @returns {mixed}
*/
nth(index) {
this._prepare();
const abs_index = Math.abs(index);
if (!Number.isInteger(index) || this.count() < abs_index || index == 0)
return null;
return index > 0
? this._jsonContent[index - 1]
: this._jsonContent[this.count() + index];
}
/**
* exists - Check if the content is empty or null
*
* @returns {boolean}
*/
exists() {
this._prepare();
if (Array.isArray(this._jsonContent)) {
return this._jsonContent.length > 0;
} else if (
this._jsonContent instanceof Object &&
this._jsonContent.constructor === Object
) {
return Object.keys(this._jsonContent).length > 0;
}
return !!this._jsonContent;
}
/**
* groupBy - return the grouped result by the given property
*
* @param {string} property
*
* @returns {Array}
*/
groupBy(property) {
if (!property) {
throw Error(
`A 'property' parameter must be given to groupBy() method`
);
}
this._prepare();
const groupedData = {};
this._jsonContent.forEach(data => {
if (property in data) {
if (!(data[property] in groupedData)) {
groupedData[data[property]] = [];
}
groupedData[data[property]].push(data);
}
});
this._jsonContent = groupedData;
return this;
}
/**
* sort - return the sorted result of the given collection.
* By default, the result would be sorted as 'Ascending'. If you want to
* sort the result as 'Descending', pass 'desc' as the parameter.
* If you want to define a different logic for sorting, pass a compare
* Function as parameter.
*
* This method should be used for array of integers or floats.
* If you want to sort an array of Objects by a specific property,
* use sortBy() method.
*
* @param {string|Function} [order=asc]
*
* @returns {mixed}
*/
sort(order = 'asc') {
this._prepare();
if (!Array.isArray(this._jsonContent)) {
return this;
}
this._jsonContent.sort((a, b) => {
return compare(a, b, order);
});
return this;
}
/**
* sortBy - return the sorted result of the given collection by the given
* property.
* By default, the result would be sorted as 'Ascending'. If you want to
* sort the result as 'Descending', pass 'desc' as the second parameter.
* If you want to define a different logic for sorting, pass a compare
* Function as second parameter.
*
* This method should be used for array of Objects.
* If you want to sort an array of integers or floats, use sort() method.
*
* @param {string} property
* @param {string|Function} property
* @returns {mixed}
* @throws {Error}
*/
sortBy(property, order = 'asc') {
if (!property) {
throw Error(
`A 'property' parameter must be given to sortAs() method`
);
}
this._prepare();
if (!Array.isArray(this._jsonContent)) {
return this;
}
this._jsonContent.sort((a, b) => {
if (a instanceof Object && property in a) {
a = a[property];
}
if (b instanceof Object && property in b) {
b = b[property];
}
return compare(a, b, order);
});
return this;
}
}
module.exports = JSJsonQ;