Completed
Push — master ( 6f3252...36e2ac )
by Chris
01:22
created

jsondash.util.intervalStrToMS   C

Complexity

Conditions 11
Paths 8

Size

Total Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 41
rs 5.2653

How to fix   Complexity   

Complexity

Complex classes like jsondash.util.intervalStrToMS often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/**
2
 * Utility functions.
3
 */
4
5
jsondash = jsondash || {util: {}};
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable jsondash is declared in the current environment, consider using typeof jsondash === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
Bug introduced by
The variable jsondash seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.jsondash.
Loading history...
6
7
jsondash.util.getCSSClasses = function(conf, defaults) {
8
    var classes = {};
9
    if(conf.classes === undefined && defaults !== undefined) {
10
        $.each(defaults, function(i, klass){
11
            classes[klass] = true;
12
        });
13
        return classes;
14
    }
15
    if(conf.classes !== undefined) {
16
        $.each(conf.classes, function(i, klass){
17
            classes[klass] = true;
18
        });
19
    }
20
    return classes;
21
};
22
23
jsondash.util.getValidParamString = function(arr) {
24
    // Jquery $.serialize and $.serializeArray will
25
    // return empty query parameters, which is undesirable and can
26
    // be error prone for RESTFUL endpoints.
27
    // e.g. `foo=bar&bar=` becomes `foo=bar`
28
    var param_str = '';
29
    arr = arr.filter(function(param, i){return param.value !== '';});
0 ignored issues
show
Unused Code introduced by
The parameter i is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
30
    $.each(arr, function(i, param){
31
        param_str += (param.name + '=' + param.value);
32
        if(i < arr.length - 1 && arr.length > 1) param_str += '&';
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
33
    });
34
    return param_str;
35
};
36
37
/**
38
 * [reformatQueryParams Reformat params into a query string.]
39
 * @param  {[type]} old [List of query params]
0 ignored issues
show
Documentation Bug introduced by
The parameter old does not exist. Did you maybe mean oldp instead?
Loading history...
40
 * @param  {[type]} new [List of query params]
0 ignored issues
show
Documentation Bug introduced by
The parameter new does not exist. Did you maybe mean newp instead?
Loading history...
41
 * @return {[type]}     [The new string (e.g. 'foo=bar&baz=1')]
42
        For example:
43
        old: foo=1&baz=1
44
        new: foo=2&quux=1
45
        expected: foo=2&quux=1&baz=1
46
 */
47
jsondash.util.reformatQueryParams = function(oldp, newp) {
48
    var _combined = {};
0 ignored issues
show
Unused Code introduced by
The assignment to variable _combined seems to be never used. Consider removing it.
Loading history...
49
    var combined  = '';
50
    var oldparams = {};
51
    var newparams = {};
52
    $.each(oldp.split('&'), function(i, param){
53
        param = param.split('=');
54
        oldparams[param[0]] = param[1];
55
    });
56
    $.each(newp.split('&'), function(i, param){
57
        param = param.split('=');
58
        newparams[param[0]] = param[1];
59
    });
60
    _combined = $.extend(oldparams, newparams);
61
    $.each(_combined, function(k, v){
62
        if(v !== undefined) {
63
            combined += k + '=' + v + '&';
64
        }
65
    });
66
    // Replace last ampersan if it exists.
67
    if(combined.charAt(combined.length - 1) === '&') {
68
        return combined.substring(0, combined.length - 1);
69
    }
70
    return combined;
71
};
72
73
/**
74
 * [intervalStrToMS Convert a string formatted to indicate an interval to milliseconds]
75
 * @param  {[String]} ival_fmt [The interval format string e.g. "1-d", "2-h"]
76
 * @return {[Number]} [The number of milliseconds]
77
 */
78
jsondash.util.intervalStrToMS = function(ival_fmt) {
79
    if(ival_fmt === undefined || ival_fmt === '') {
80
        return null;
81
    }
82
    // Just return number if it's a regular integer.
83
    if(!isNaN(ival_fmt)) {
84
        return ival_fmt;
85
    }
86
    var pieces = ival_fmt.split('-');
87
    var amt = parseInt(pieces[0], 10);
88
    if(pieces.length !== 2 || isNaN(amt) || amt === 0) {
89
        // Force NO value if the format is invalid.
90
        // This would be used to ensure the interval
91
        // is not set in the first place.
92
        return null;
93
    }
94
    var ival = pieces[1].toLowerCase();
95
    var ms2s = 1000;
96
    var ms2min = 60 * ms2s;
97
    var ms2hr = 60 * ms2min;
98
    var ms2day = 24 * ms2hr;
99
100
    // Seconds
101
    if(ival === 's') {
102
        return amt * ms2s;
103
    }
104
    // Minutes
105
    if(ival === 'm') {
106
        return amt * ms2min;
107
    }
108
    // Hours
109
    if(ival === 'h') {
110
        return amt * ms2hr;
111
    }
112
    // Days
113
    if(ival === 'd') {
114
        return amt * ms2day;
115
    }
116
    // Anything else is invalid.
117
    return null;
118
};
119
120
jsondash.util.serializeToJSON = function(arr) {
121
    // Convert form data to a proper json value
122
    var json = {};
123
    $.each(arr, function(_, pair){
124
        json[pair.name] = pair.value;
125
    });
126
    return json;
127
};
128
129
jsondash.util.isOverride = function(config) {
130
    return config.override && config.override === true;
131
};
132
133
// Credit: http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
134
jsondash.util.s4 = function() {
135
    return Math.floor((1 + Math.random()) * 0x10000)
136
    .toString(16)
137
    .substring(1);
138
};
139
140
jsondash.util.guid = function() {
141
    var s4 = jsondash.util.s4;
142
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
143
    s4() + '-' + s4() + s4() + s4();
144
};
145
146
jsondash.util.polygon = function(d) {
147
    return "M" + d.join("L") + "Z";
148
};
149
150
jsondash.util.scaleStr = function(x, y) {
151
    return 'scale(' + x + ',' + y + ')';
152
};
153
154
jsondash.util.translateStr = function(x, y) {
155
    return 'translate(' + x + ',' + y + ')';
156
};
157
158
/**
159
 * [getDigitSize return a d3 scale for adjusting font size based
160
 *     on digits and width of container.]
161
 */
162
jsondash.util.getDigitSize = function() {
163
    var BOX_PADDING = 20;
0 ignored issues
show
Unused Code introduced by
The variable BOX_PADDING seems to be never used. Consider removing it.
Loading history...
164
    // scale value is reversed, since we want
165
    // the font-size to get smaller as the number gets longer.
166
    var scale = d3.scale.linear()
0 ignored issues
show
Bug introduced by
The variable d3 seems to be never declared. If this is a global, consider adding a /** global: d3 */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
167
        .clamp(true)
168
        .domain([2, 14]) // min/max digits length: $0 - $999,999,999.00
169
        .range([90, 30]); // max/min font-size
170
    window.scale = scale;
171
    return scale;
172
};
173
174
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
175
    module.exports = jsondash;
176
}
177