Line data Source code
1 : type ParamValue = string[] | string | number | boolean
2 : type Params = Record<string, ParamValue | undefined>
3 :
4 137 : function sortedParams(params: Params = {}): Record<string, ParamValue> {
5 137 : const keys = Object.keys(params).sort()
6 137 : const obj: Record<string, ParamValue> = {}
7 137 : for (const k of keys) {
8 599 : const v = params[k]
9 599 : if (v === undefined) continue
10 599 : obj[k] = Array.isArray(v) ? [...v].sort((a, b) => a.localeCompare(b)) : v
11 : }
12 137 : return obj
13 : }
14 :
15 137 : export function encodeParams(params: Params = {}) {
16 137 : const sorted = sortedParams(params)
17 : const parts = Object.entries(sorted).map(([key, value]) => {
18 527 : const encoded = Array.isArray(value)
19 : ? value.map(String).map(encodeURIComponent).join(',')
20 : : encodeURIComponent(String(value))
21 527 : return `${encodeURIComponent(key)}=${encoded}`
22 : })
23 137 : return parts.join('&')
24 : }
|