Created
October 29, 2022 09:31
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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