1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | module.exports = class IndexHelper {
|
7 |
|
8 | static indexObjects (items, keyProp, valueProp) {
|
9 | const result = {};
|
10 | if (!Array.isArray(items)) {
|
11 | return result;
|
12 | }
|
13 | for (const item of items) {
|
14 | if (item !== null && item !== undefined) {
|
15 | result[item[keyProp]] = valueProp === undefined ? item : item[valueProp];
|
16 | }
|
17 | }
|
18 | return result;
|
19 | }
|
20 |
|
21 | static indexObjectArrays (docs, keyProp, valueProp) {
|
22 | const result = {};
|
23 | if (!Array.isArray(docs)) {
|
24 | return result;
|
25 | }
|
26 | for (const doc of docs) {
|
27 | if (doc) {
|
28 | const value = valueProp === undefined ? doc : doc[valueProp];
|
29 | if (Array.isArray(result[doc[keyProp]])) {
|
30 | result[doc[keyProp]].push(value);
|
31 | } else {
|
32 | result[doc[keyProp]] = [value];
|
33 | }
|
34 | }
|
35 | }
|
36 | return result;
|
37 | }
|
38 |
|
39 | static indexModels (models, keyAttr, valueAttr) {
|
40 | const result = {};
|
41 | if (Array.isArray(models)) {
|
42 | for (const model of models) {
|
43 | result[model.get(keyAttr)] = valueAttr ? model.get(valueAttr) : model;
|
44 | }
|
45 | }
|
46 | return result;
|
47 | }
|
48 |
|
49 | static indexModelArrays (models, keyAttr, valueAttr) {
|
50 | const result = {};
|
51 | if (!Array.isArray(models)) {
|
52 | return result;
|
53 | }
|
54 | for (const model of models) {
|
55 | const value = valueAttr ? model.get(valueAttr) : model;
|
56 | const key = model.get(keyAttr);
|
57 | if (Array.isArray(result[key])) {
|
58 | result[key].push(value);
|
59 | } else {
|
60 | result[key] = [value];
|
61 | }
|
62 | }
|
63 | return result;
|
64 | }
|
65 | }; |
\ | No newline at end of file |