Passed
Push — master ( f566f3...fdd3db )
by Paul
04:45
created

+/scripts/public/helper-functions.js   C

Complexity

Total Complexity 60
Complexity/F 3.16

Size

Lines of Code 187
Function Count 19

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
nc 294912
dl 0
loc 187
rs 5.1111
c 1
b 0
f 0
wmc 60
mnd 4
bc 44
fnc 19
bpm 2.3157
cpm 3.1578
noi 4

13 Functions

Rating   Name   Duplication   Size   Complexity  
A GLSR.postAjax 0 14 3
B GLSR.serialize 0 14 5
A GLSR.isString 0 3 1
A GLSR.appendTo 0 5 1
B GLSR.parseFormData 0 55 6
B GLSR.convertValue 0 15 6
A GLSR.insertAfter 0 5 1
A GLSR.createEl 0 9 4
A GLSR.getAjax 0 12 2
A GLSR.ready 0 19 4
A GLSR.isNumeric 0 3 1
A GLSR.on 0 8 2
A GLSR.off 0 8 2

How to fix   Complexity   

Complexity

Complex classes like +/scripts/public/helper-functions.js 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
var GLSR = {};
2
3
GLSR.convertValue = function( value ) {
4
	if( GLSR.isNumeric( value )) {
5
		return parseFloat( value );
6
	}
7
	else if( value === 'true') {
8
		return true;
9
	}
10
	else if( value === 'false' ) {
11
		return false;
12
	}
13
	else if( value === '' || value === null ) {
14
		return undefined;
15
	}
16
	return value;
17
};
18
19
GLSR.getAjax = function( url, success ) {
20
	var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject( 'Microsoft.XMLHTTP' );
0 ignored issues
show
Bug introduced by
The variable XMLHttpRequest seems to be never declared. If this is a global, consider adding a /** global: XMLHttpRequest */ 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...
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ 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...
21
	xhr.open( 'GET', url );
22
	xhr.onreadystatechange = function() {
23
		if( xhr.readyState > 3 && xhr.status === 200 ) {
24
			success( xhr.responseText );
25
		}
26
	};
27
	xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' );
28
	xhr.send();
29
	return xhr;
30
};
31
32
GLSR.isNumeric = function( value ) {
33
	return !( isNaN( parseFloat( value )) || !isFinite( value ));
34
};
35
36
GLSR.isString = function( str ) {
37
	return Object.prototype.toString.call( str ) === '[object String]';
38
};
39
40
GLSR.on = function( type, el, handler ) {
41
	if( GLSR.isString( el )) {
42
		el = document.querySelectorAll( el );
43
	}
44
	[].forEach.call( el, function( node ) {
45
		node.addEventListener( type, handler );
46
	});
47
};
48
49
GLSR.off = function( type, el, handler ) {
50
	if( GLSR.isString( el )) {
51
		el = document.querySelectorAll( el );
52
	}
53
	[].forEach.call( el, function( node ) {
54
		node.removeEventListener( type, handler );
55
	});
56
};
57
58
/**
59
 * Adapted from https://github.com/bitovi/jquerypp/blob/master/dom/form_params/form_params.js
60
 */
61
GLSR.parseFormData = function( form, convert ) {
62
	convert = !!convert || false;
63
	var keyBreaker = /[^\[\]]+/g; // used to parse bracket notation
64
	var data = {};
65
	var seen = {}; // used to uniquely track seen values
66
	var nestData = function( field, data, parts, seenName )
67
	{
68
		var name = parts.shift();
69
		// Keep track of the dot separated fullname
70
		seenName = seenName ? seenName + '.' + name : name;
71
		if( parts.length ) {
72
			if( !data[ name ] ) {
73
				data[ name ] = {};
74
			}
75
			// Recursive call
76
			nestData( field, data[ name ], parts, seenName );
77
		}
78
		else {
79
			// Convert the value
80
			var value = convert ? GLSR.convertValue( field.value ) : field.value;
81
			// Handle same name case, as well as "last checkbox checked" case
82
			if( seenName in seen && field.type !== 'radio' && !data[ name ].isArray()) {
83
				if( name in data ) {
84
					data[ name ] = [ data[name] ];
85
				}
86
				else {
87
					data[ name ] = [];
88
				}
89
			}
90
			else {
91
				seen[ seenName ] = true;
92
			}
93
			// Finally, assign data
94
			if( ['radio','checkbox'].indexOf( field.type ) !== -1 && !field.checked )return;
95
96
			if( !data[ name ] ) {
97
				data[ name ] = value;
98
			}
99
			else {
100
				data[ name ].push( value );
101
			}
102
		}
103
	};
104
105
	for( var i = 0; i < form.length; i++ ) {
106
		var field = form[i];
107
		if( !field.name || field.disabled || ['file','reset','submit','button'].indexOf( field.type ) !== -1 )continue;
108
		var parts = field.name.match( keyBreaker );
109
		if( !parts.length ) {
110
			parts = [ field.name ];
111
		}
112
		nestData( field, data, parts );
113
	}
114
	return data;
115
};
116
117
GLSR.postAjax = function( url, data, success ) {
118
	var params = typeof data !== 'string' ? GLSR.serialize( data ) : data;
119
	var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject( 'Microsoft.XMLHTTP' );
0 ignored issues
show
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ 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...
Bug introduced by
The variable XMLHttpRequest seems to be never declared. If this is a global, consider adding a /** global: XMLHttpRequest */ 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...
120
	xhr.open( 'POST', url ); // asynchronously
121
	xhr.onreadystatechange = function() {
122
		if( xhr.readyState > 3 && xhr.status === 200 ) {
123
			success( JSON.parse( xhr.responseText ));
124
		}
125
	};
126
	xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' );
127
	xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' );
128
	xhr.send( params );
129
	return xhr;
130
};
131
132
GLSR.ready = function( fn ) {
133
	if( typeof fn !== 'function' )return;
134
	// in case the document is already rendered
135
	if( document.readyState !== 'loading' ) {
136
		fn();
137
	}
138
	// modern browsers
139
	else if( document.addEventListener ) {
140
		document.addEventListener( 'DOMContentLoaded', fn );
141
	}
142
	// IE <= 8
143
	else {
144
		document.attachEvent( 'onreadystatechange', function() {
145
			if( document.readyState === 'complete' ) {
146
				fn();
147
			}
148
		});
149
	}
150
};
151
152
GLSR.serialize = function( obj, prefix ) {
153
	var str = [];
154
155
	for( var property in obj ) {
156
		if( !obj.hasOwnProperty( property ))continue;
157
		var key = prefix ? prefix + '[' + property + ']' : property;
158
		var value = obj[ property ];
159
		str.push( typeof value === 'object' ?
160
			GLSR.serialize( value, key ) :
161
			encodeURIComponent( key ) + '=' + encodeURIComponent( value )
162
		);
163
	}
164
	return str.join( '&' );
165
};
166
167
GLSR.insertAfter = function( el, tag, attributes ) {
168
	var newEl = GLSR.createEl( tag, attributes );
169
	el.parentNode.insertBefore( newEl, el.nextSibling );
170
	return newEl;
171
};
172
173
GLSR.appendTo = function( el, tag, attributes ) {
174
	var newEl = GLSR.createEl( tag, attributes );
175
	el.appendChild( newEl );
176
	return newEl;
177
};
178
179
GLSR.createEl = function( tag, attributes ) {
180
	var el = ( typeof tag === 'string' ) ? document.createElement( tag ) : tag;
181
	attributes = attributes || {};
182
	for( var key in attributes ) {
183
		if( !attributes.hasOwnProperty( key ) )continue;
184
		el.setAttribute( key, attributes[ key ] );
185
	}
186
	return el;
187
};
188