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

index.js ➔ ... ➔ ???   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 5
nop 2
dl 0
loc 13
rs 8.8571
c 0
b 0
f 0
1
import App from "app";
2
3
App.helpers.array = {};
4
5
/**
6
 * Sort an array of objects by one prop of objects
7
 * @param {Array} data
8
 * @param {String} prop
9
 * @param {String} direction defines if sort should be asc or desc
10
 */
11
App.helpers.array.sortByObjectKey = (data, prop, direction = "asc") => {
12
    if (["asc", "desc"].indexOf(direction) === -1) {
13
        throw new Error("Direction should be asc or desc");
14
    }
15
16
    return data.sort((a, b) => {
17
        let response = 0,
18
            ap = a[prop],
19
            bp = b[prop];
20
21
        if (ap < bp) {
22
            response = direction === "asc" ? -1 : 1;
23
        } else if (ap > bp) {
24
            response = direction === "asc" ? 1 : -1;
25
        }
26
27
        return response;
28
    });
29
};
30
31
/**
32
 * Filter objects from array that has key value in values
33
 * Example:
34
 * var a = [{a: 1}, {a: 2}, {a: 3}]
35
 * App.helpers.array.filterBy("a", [1, 3], a);
36
 *
37
 * The output will be:
38
 * [{a: 1}, {a: 3}]
39
 * @param key
40
 * @param values
41
 * @param items
42
 */
43
App.helpers.array.filterBy = (key, values, items) => {
44
    "use strict";
45
46
    return items.filter(item => values.indexOf(item[key]) > -1);
47
};
48