Passed
Push — master ( c83a47...2e74fa )
by Andreas
26:58
created

chart.js ➔ init_chart   B

Complexity

Conditions 8

Size

Total Lines 51
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 32
dl 0
loc 51
rs 7.2453
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
function init_chart(grid_id) {
2
3
    const ctx = document.getElementById('chart-' + grid_id);
4
    var chart;
5
6
    function render_grid() {
7
        let group_data = $('#' + grid_id).jqGrid('getGridParam', 'groupingView'),
8
        chart_labels = [],
9
        chart_data = [];
10
11
        group_data.groups.forEach(function(group) {
12
            chart_labels.push(group.value.replace(/<\/?[^>]+(>|$)/g, ""));
13
            chart_data.push(group.summary[0].v);
14
        });
15
16
        var label = '';
17
        $('#' + grid_id).jqGrid('getGridParam', 'colModel').forEach(function(col, index) {
18
            if (col.name == 'sum') {
19
                label = $('#' + grid_id).jqGrid('getGridParam', 'colNames')[index];
20
            }
21
        });
22
23
        chart = new Chart(ctx, {
24
        type: 'bar',
25
        data: {
26
            labels: chart_labels,
27
            datasets: [{
28
                label: label,
29
                data: chart_data,
30
                borderWidth: 1
31
            }]
32
        },
33
        options: {
34
            scales: {
35
            y: {
36
                beginAtZero: true
37
            }
38
            }
39
        }
40
        });
41
    }
42
43
    $('#chgrouping_' + grid_id).on('change', function() {
44
        if (chart) {
45
            chart.destroy();
46
        }
47
        if ($('#' + grid_id).jqGrid('getGridParam', 'grouping')) {
48
            render_grid();
49
        }
50
    }).trigger('change');
51
}