UNPKG

1.32 kBJavaScriptView Raw
1// more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even
2// though these characters have no formalized URI delimiting uses, see
3// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
4// for more details
5function encodeURICom (str) {
6 return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
7 return '%' + c.charCodeAt(0).toString(16)
8 })
9}
10
11function encoderForArrayFormat (key, value) {
12 if (value === null) return encodeURICom(key)
13 return [encodeURICom(key), '=', encodeURICom(value)].join('')
14}
15
16function stringify (obj) {
17 if (!obj) return ''
18 var keys = Object.keys(obj)
19 // keys.sort(options.sort)
20 var out = []
21 for (var k = 0; k < keys.length; k++) {
22 var key = keys[k]
23 var param = ''
24 var value = obj[key]
25 if (value === undefined) continue
26 if (value === null) {
27 param = encodeURICom(key)
28 } else if (!Array.isArray(value)) {
29 param = encodeURICom(key) + '=' + encodeURICom(value)
30 } else {
31 // array
32 var arr = []
33 for (var i = 0; i < value.length; i++) {
34 if (value[i] === undefined) continue
35 arr.push(encoderForArrayFormat(key, value[i], arr.length))
36 }
37 param = arr.join('&')
38 }
39 if (param.length > 0) out.push(param)
40 }
41 return out.join('&')
42}
43
44module.exports = { stringify: stringify }