-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathHelpers.js
90 lines (79 loc) · 1.97 KB
/
Helpers.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
/**
* parseJson - parse Json Data from a given filePath
* or a Json String or Json Object
*
* @param {string|Object} json
*
* @returns {Object} the parsed Json Object
* @throws {Error}
*/
const parseJson = json => {
let jsonObject = json;
if (
(typeof json === 'string' || json instanceof String) &&
json.endsWith('.json')
) {
jsonObject = require.resolve(`${json}`);
}
if (typeof jsonObject === 'string' || jsonObject instanceof String) {
try {
jsonObject = JSON.parse(json);
} catch (e) {
throw Error('Invalid Json data');
}
}
if (!(Array.isArray(jsonObject) || jsonObject instanceof Object)) {
throw Error('Invalid Json data');
}
return jsonObject;
};
/**
* getByProperty - get the content of the Data by the given property
*
* @param {string} property
* @param {Array|Object} data
*
* @returns {mixed}
* @throws {Error}
*/
const getByProperty = (property, data) => {
if (!(property in data)) {
throw Error('Data not exists');
}
return data[property];
};
/**
* compare - compare the values based on the given ordering (could be ascending,
* descending or by the given method )
*
* @param {int|float|string} a
* @param {int|float|string} b
* @param {string|Function} order
*
* @returns {int} 0 or 1 or -1
*/
const compare = (a, b, order) => {
//if a comparison method is given as third parameter
if (order instanceof Function) {
return order(a, b);
} else {
if (typeof a === 'string' || a instanceof String) {
a = a.toLowerCase();
}
if (typeof b === 'string' || b instanceof String) {
b = b.toLowerCase();
}
//comparison
if (a < b) {
return order == 'asc' ? -1 : 1;
} else if (a > b) {
return order == 'asc' ? 1 : -1;
}
return 0;
}
};
module.exports = {
parseJson,
getByProperty,
compare
};