Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created March 30, 2020 20:07
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 aleclarson/f64395c02ea8190cd8dacd33e45e499d to your computer and use it in GitHub Desktop.
Save aleclarson/f64395c02ea8190cd8dacd33e45e499d to your computer and use it in GitHub Desktop.
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