Completed
Branch es2015 (569745)
by Luís
02:57
created

index.js ➔ ???   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 4
nop 3
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
1
import App from "app";
2
3
App.helpers.object = {};
4
5
/**
6
 * Get element from obj by string path
7
 * Example:
8
 * Given the object let a = {a: {b: 1}}
9
 * When you do getFlattened("a.b", a)
10
 * Then you get the number 1.
11
 * @param {string} path specify the key of the object you want
12
 * @param {Object} obj reference object
13
 * @param {any} defaultValue value to return if key was not found. Default is null
14
 * @return {any}
15
 */
16
App.helpers.object.getFlattened = (path, obj, defaultValue = null) => {
17
    if (typeof path !== "string") {
18
        throw "path must be string";
19
    }
20
21
    let i;
22
    let response = obj;
23
    const size = path.split(".").length;
24
25
    for (i = 0; i < size; i += 1) {
26
        if (response instanceof Object === false) {
27
            return defaultValue;
28
        }
29
30
        if (response.hasOwnProperty(path[i])) {
31
            response = response[path[i]];
32
        } else {
33
            return defaultValue;
34
        }
35
    }
36
37
    return response;
38
};
39
40
/**
41
 * @see getFlattened
42
 * Similar to getFlattened, but it set the value instead of return it.
43
 * Example:
44
 * Given the object let b = {a: {b: 1}}
45
 * When you do setFlattened("a.b", 2)
46
 * Then you get {a: {b: 2}}
47
 * @param {String} path
48
 * @param {*} newValue
49
 * @param {Object} obj
50
 * @returns {*}
51
 */
52
App.helpers.object.setFlattened = (path, newValue, obj) => {
53
    "use strict";
54
55
    const laps = path.split(".").length;
56
    let i;
57
    let temp = obj;
58
59
    for (i = 0; i < laps; i += 1) {
60
        temp = temp[path[i]];
61
    }
62
63
    temp[path[laps]] = newValue;
64
    return obj;
65
};
66
67
/**
68
 * Get first key of an object or null if it doesn't have keys
69
 * @param {Object} obj
70
 * @returns {*}
71
 */
72
App.helpers.object.firstKey = (obj) => {
73
    "use strict";
74
75
    if (obj instanceof Object === false) {
76
        throw "obj must be an Object";
77
    }
78
79
    return Object.keys(obj)[0] || null;
80
};
81