Completed
Pull Request — master (#2)
by Luís
02:08 queued 01:01
created

src/js/helpers/array/index.js   A

Complexity

Total Complexity 9
Complexity/F 2.25

Size

Lines of Code 47
Function Count 4

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 0
nc 4
dl 0
loc 47
rs 10
c 2
b 0
f 1
wmc 9
mnd 3
bc 6
fnc 4
bpm 1.5
cpm 2.25
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A index.js ➔ ??? 0 19 2
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