-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
137 lines (115 loc) · 2.36 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// starparam - URL Parameter Utility
//
// https://github.com/jonbri/starparam
// https://www.npmjs.com/package/starparam
//
// Jonathan Brink <jonathandavidbrink@gmail.com>
//
// utility functions
//
function isNil(s) {
return s === null || s === undefined;
}
function getParamObject(sUrl, sParam) {
return parse(sUrl).params.filter(oParam => oParam.name === sParam)[0];
}
//
// api functions
//
function parse(sUrl) {
if (isNil(sUrl)) {
return undefined;
}
const aMatches = new RegExp(
'(^[^?&#]+)' + // prefix
'\\??' +
'([^#]*)' + // params
'#?' +
'(.*)$' // hash
).exec(sUrl);
if (isNil(aMatches)) {
return {
params: []
};
}
return {
prefix: aMatches[1],
params: aMatches[2]
.split('&')
.filter(s => s !== '')
.map(s => s.split('='))
.map(a => ({ name: a[0], value: a[1] })),
hash: aMatches[3] === '' ? undefined : aMatches[3]
};
}
function get(sUrl, sParam) {
if (isNil(sUrl) || isNil(sParam)) {
return undefined;
}
const oMatch = getParamObject(sUrl, sParam);
return isNil(oMatch) ? undefined : oMatch.value;
}
function set(sUrl, sParam, sValue) {
if (isNil(sUrl) || isNil(sParam)) {
return undefined;
}
if (isNil(sValue)) {
sValue = '';
}
const oUrl = parse(sUrl);
if (isNil(getParamObject(sUrl, sParam))) {
oUrl.params.push({
name: sParam,
value: sValue
});
} else {
oUrl.params = oUrl.params.map(oParam => {
if (oParam.name === sParam) {
oParam.value = sValue;
}
return oParam;
});
}
return stringify(oUrl);
}
function remove(sUrl, sParam) {
if (isNil(sUrl)) {
return undefined;
}
if (isNil(sParam)) {
return sUrl;
}
const oUrl = parse(sUrl);
oUrl.params = oUrl.params.filter(oParam => oParam.name !== sParam);
return stringify(oUrl);
}
function stringify(o) {
let sResult = '';
if (isNil(o)) {
return undefined;
}
if (isNil(o.prefix) === false) {
sResult += o.prefix;
}
if (isNil(o.params) === false) {
o.params.forEach((oParam, iIndex) => {
if (iIndex === 0) {
sResult += '?';
} else {
sResult += '&';
}
sResult += oParam.name + '=' + oParam.value;
});
}
if (isNil(o.hash) === false) {
sResult += '#' + o.hash;
}
return sResult;
}
module.exports = {
parse,
get,
set,
remove,
stringify
};