Skip to content

Instantly share code, notes, and snippets.

@lightningspirit
Created October 29, 2022 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lightningspirit/26011319aa7b118e6b2dc7c5fc95fd90 to your computer and use it in GitHub Desktop.
Save lightningspirit/26011319aa7b118e6b2dc7c5fc95fd90 to your computer and use it in GitHub Desktop.
A function that takes an object and outputs a query string. Booleans are mapped into 1 and 0. Supports arrays of values.
type ValueType =
| string
| number
| boolean
| null
| undefined
| (string | number | boolean | null | undefined)[]
function mapBooleans(key: string, value: ValueType) {
switch (value) {
case true:
return `${key}=1`
case false:
return `${key}=0`
default:
return `${key}=${value}`
}
}
const buildQueryString = (
query: Record<string, string | number | null | boolean | undefined>,
) =>
Object.entries(query)
.filter(([, value]) => value !== undefined || value !== null)
.map(([key, value]) => {
if (Array.isArray(value)) {
return value.map
}
return mapBooleans(key, value)
})
.join("&")
export default buildQueryString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment