-
Notifications
You must be signed in to change notification settings - Fork 1
/
stringify.ts
41 lines (34 loc) · 927 Bytes
/
stringify.ts
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
// based on: https://github.com/Gozala/querystring/blob/master/encode.js
const stringifyPrimitive = function(v: any): string | number {
switch (typeof v) {
case 'string':
return v
case 'boolean':
return v ? 'true' : 'false'
case 'number':
return isFinite(v) ? v : ''
default:
return ''
}
}
module.exports = function(obj: any): string {
if (!obj) return ''
const sep = '&'
const eq = '='
return Object.keys(obj)
.map(function(k) {
const ks = encodeURIComponent(stringifyPrimitive(k)) + eq
if (Array.isArray(obj[k])) {
return obj[k]
.map(function(v: any) {
return ks + encodeURIComponent(stringifyPrimitive(v))
})
.join(sep)
} else {
if (obj[k] === undefined) return ''
return ks + encodeURIComponent(stringifyPrimitive(obj[k]))
}
})
.filter(Boolean)
.join(sep)
}