UNPKG

2.34 kBJavaScriptView Raw
1exports.getQueryParams = function getQueryParams(qs) {
2 if (typeof qs !== 'string') {
3 return {};
4 }
5 qs = qs.split('+').join(' ');
6
7 var params = {};
8 var match = qs.match(
9 /(?:[?](?:[^=]+)=(?:[^&#]*)(?:[&](?:[^=]+)=(?:[^&#]*))*(?:[#].*)?)|(?:[#].*)/
10 );
11 var split;
12
13 if (match === null) {
14 return {};
15 }
16
17 split = match[0].substr(1).split(/[&#=]/);
18
19 for (var i = 0; i < split.length; i += 2) {
20 params[decodeURIComponent(split[i])] =
21 decodeURIComponent(split[i + 1] || '');
22 }
23
24 return params;
25};
26
27exports.combineParams = function combineParams(op) {
28 if (typeof op !== 'object') {
29 return '';
30 }
31 op.params = op.params || {};
32 var combined = '',
33 i = 0,
34 keys = Object.keys(op.params);
35
36 if (keys.length === 0) {
37 return '';
38 }
39
40 //always have parameters in the same order
41 keys.sort();
42
43 if (!op.hasParams) {
44 combined += '?' + keys[0] + '=' + op.params[keys[0]];
45 i += 1;
46 }
47
48 for (; i < keys.length; i += 1) {
49 combined += '&' + keys[i] + '=' + op.params[keys[i]];
50 }
51 return combined;
52};
53
54//parses strings like 1h30m20s to seconds
55function getLetterTime(timeString) {
56 var totalSeconds = 0;
57 var timeValues = {
58 's': 1,
59 'm': 1 * 60,
60 'h': 1 * 60 * 60,
61 'd': 1 * 60 * 60 * 24,
62 'w': 1 * 60 * 60 * 24 * 7,
63 };
64 var timePairs;
65
66 //expand to "1 h 30 m 20 s" and split
67 timeString = timeString.replace(/([smhdw])/g, ' $1 ').trim();
68 timePairs = timeString.split(' ');
69
70 for (var i = 0; i < timePairs.length; i += 2) {
71 totalSeconds += parseInt(timePairs[i], 10) *
72 timeValues[timePairs[i + 1] || 's'];
73 }
74 return totalSeconds;
75}
76
77//parses strings like 1:30:20 to seconds
78function getColonTime(timeString) {
79 var totalSeconds = 0;
80 var timeValues = [
81 1,
82 1 * 60,
83 1 * 60 * 60,
84 1 * 60 * 60 * 24,
85 1 * 60 * 60 * 24 * 7,
86 ];
87 var timePairs = timeString.split(':');
88 for (var i = 0; i < timePairs.length; i++) {
89 totalSeconds += parseInt(timePairs[i], 10) * timeValues[timePairs.length - i - 1];
90 }
91 return totalSeconds;
92}
93
94exports.getTime = function getTime(timeString) {
95 if (typeof timeString === 'undefined') {
96 return 0;
97 }
98 if (timeString.match(/^(\d+[smhdw]?)+$/)) {
99 return getLetterTime(timeString);
100 }
101 if (timeString.match(/^(\d+:?)+$/)) {
102 return getColonTime(timeString);
103 }
104 return 0;
105};
\No newline at end of file