Skip to content

Instantly share code, notes, and snippets.

@yuku
Created August 16, 2017 02:10
Show Gist options
  • Save yuku/e568b9134aeeabcc7cde270849e109bf to your computer and use it in GitHub Desktop.
Save yuku/e568b9134aeeabcc7cde270849e109bf to your computer and use it in GitHub Desktop.
// @flow
type Params = {
[string]: string | number | null | Array<string | number | null>
}
function encode(val: string | number) {
return encodeURIComponent(val + '').
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']')
}
function serializeParams(params: Params) {
return Object.keys(params)
.map(key => {
const value = params[key]
if (value == null) return
return Array.isArray(value) ? [`${key}[]`, value] : [key, [value]]
})
.reduce(function (parts, entry) {
if (entry == null) return parts
const [key, value] = entry
return parts.concat(value.filter(v => v).map(v => {
if (v instanceof Date) {
v = v.toISOString()
} else if (v instanceof Object) {
v = JSON.stringify(v)
}
return v ? `${encode(key)}=${encode(v)}` : v
}))
}, [])
.join("&")
}
function buildURL(url: string, params: ?Params) {
return params ? `${url}${url.indexOf("?") === -1 ? "?" : "&"}${serializeParams(params)}` : url
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment