Completed
Push — master ( d7418f...2e3d01 )
by Chris
01:23
created

jsondash.util.reformatQueryParams   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 3
Metric Value
cc 1
dl 0
loc 4
rs 10
c 3
b 0
f 3
nc 1
nop 2
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
    // Just return number if it's a regular integer.
80
    if(!isNaN(ival_fmt)) {
81
        return ival_fmt;
82
    }
83
    var pieces = ival_fmt.split('-');
84
    var amt = parseInt(pieces[0], 10);
85
    if(pieces.length !== 2 || isNaN(amt) || amt === 0) {
86
        // Force NO value if the format is invalid.
87
        // This would be used to ensure the interval
88
        // is not set in the first place.
89
        return null;
90
    }
91
    var ival = pieces[1].toLowerCase();
92
    var ms2s = 1000;
93
    var ms2min = 60 * ms2s;
94
    var ms2hr = 60 * ms2min;
95
    var ms2day = 24 * ms2hr;
96
97
    // Seconds
98
    if(ival === 's') {
99
        return amt * ms2s;
100
    }
101
    // Minutes
102
    if(ival === 'm') {
103
        return amt * ms2min;
104
    }
105
    // Hours
106
    if(ival === 'h') {
107
        return amt * ms2hr;
108
    }
109
    // Days
110
    if(ival === 'd') {
111
        return amt * ms2day;
112
    }
113
    // Anything else is invalid.
114
    return null;
115
};
116
117
jsondash.util.serializeToJSON = function(arr) {
118
    // Convert form data to a proper json value
119
    var json = {};
120
    $.each(arr, function(_, pair){
121
        json[pair.name] = pair.value;
122
    });
123
    return json;
124
};
125
126
jsondash.util.isOverride = function(config) {
127
    return config.override && config.override === true;
128
};
129
130
// Credit: http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
131
jsondash.util.s4 = function() {
132
    return Math.floor((1 + Math.random()) * 0x10000)
133
    .toString(16)
134
    .substring(1);
135
};
136
137
jsondash.util.guid = function() {
138
    var s4 = jsondash.util.s4;
139
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
140
    s4() + '-' + s4() + s4() + s4();
141
};
142
143
jsondash.util.polygon = function(d) {
144
    return "M" + d.join("L") + "Z";
145
};
146
147
jsondash.util.scaleStr = function(x, y) {
148
    return 'scale(' + x + ',' + y + ')';
149
};
150
151
jsondash.util.translateStr = function(x, y) {
152
    return 'translate(' + x + ',' + y + ')';
153
};
154
155
/**
156
 * [getDigitSize return a d3 scale for adjusting font size based
157
 *     on digits and width of container.]
158
 */
159
jsondash.util.getDigitSize = function() {
160
    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...
161
    // scale value is reversed, since we want
162
    // the font-size to get smaller as the number gets longer.
163
    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...
164
        .clamp(true)
165
        .domain([2, 14]) // min/max digits length: $0 - $999,999,999.00
166
        .range([90, 30]); // max/min font-size
167
    window.scale = scale;
168
    return scale;
169
};
170
171
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
172
    module.exports = jsondash;
173
}
174