-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
114 lines (93 loc) · 2.13 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
'use strict'
stringify.serialize = serialize
stringify.shake = shake
stringify.normalize = normalize
stringify.appendToUrl = appendToUrl
stringify.stringify = stringify
module.exports = stringify
function appendToUrl(url, i) {
const qs = stringify(i)
if (qs === '') return url
return url + '?' + qs
}
function stringify(i) {
if (i === null || typeof i !== 'object' || Array.isArray(i)) {
throw new Error('Only objects can be stringified')
}
const shaken = shake(normalize(i))
if (shaken === undefined) return ''
return serialize(shaken)
}
function serialize(i, prefix) {
if (Array.isArray(i)) {
const hasComplex = i.some(isComplex)
return i
.map((i, idx) => {
return serialize(
i,
prefix + (hasComplex ? '[' + idx + ']' : '[]')
)
})
.join('&')
}
if (typeof i === 'object') {
return Object.keys(i)
.map((key) => {
return serialize(
i[key],
prefix === undefined
? encodeURIComponent(key)
: prefix + '[' + encodeURIComponent(key) + ']'
)
})
.join('&')
}
return prefix + '=' + encodeURIComponent(i)
}
function shake(i) {
if (i === undefined) return
if (Array.isArray(i)) {
const shaken = i.map(shake).filter(isDefined)
if (shaken.length === 0) return
return shaken
}
if (typeof i === 'object') {
let empty = true
const shaken = Object.keys(i).reduce((o, key) => {
const shaken = shake(i[key])
if (shaken !== undefined) {
empty = false
o[key] = shaken
}
return o
}, {})
if (empty) return
return shaken
}
return i
}
function normalize(i) {
if (i === undefined) return undefined
if (i === null) return ''
if (i === true) return 'y'
if (i === false) return 'n'
if (typeof i.toJSON === 'function') return normalize(i.toJSON())
const type = typeof i
if (type === 'string') return i
if (Array.isArray(i)) return i.map(normalize)
if (type === 'object') {
return Object.keys(i).reduce((o, key) => {
o[key] = normalize(i[key])
return o
}, {})
}
return i + ''
}
function isDefined(i) {
return i !== undefined
}
function isComplex(i) {
if (Array.isArray(i)) return true
if (typeof i === 'object') return true
return false
}