Created
March 30, 2020 20:07
-
-
Save aleclarson/f64395c02ea8190cd8dacd33e45e499d to your computer and use it in GitHub Desktop.
This file contains 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
import { is } from 'is' | |
import { Lookup } from 'types' | |
// Reuse one array for all encoding. | |
const pairs: string[] = [] | |
export function encodeForm(values: Lookup) { | |
for (const key in values) { | |
encodePair(key, values[key]) | |
} | |
const str = pairs.join('&') | |
pairs.length = 0 | |
return str | |
} | |
function encodePair(key: string, value: any) { | |
if (is.defined(value)) { | |
if (is.object(value)) { | |
encodeObject(value, key) | |
} else if (is.array(value)) { | |
encodeArray(value, key) | |
} else { | |
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)) | |
} | |
} | |
} | |
function encodeObject(values: Lookup, parent: string) { | |
for (const key in values) { | |
encodePair(parent + '[' + key + ']', values[key]) | |
} | |
} | |
function encodeArray(values: readonly any[], parent: string) { | |
for (let i = 0; i < values.length; i++) { | |
encodePair(parent + '[' + i + ']', values[i]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment