expect(stringifyQuery({ e: undefined, b: 'a' })).toEqual('b=a')
})
- it('ignores undefined and empty arrays', () => {
- expect(
- stringifyQuery({ a: [undefined, 'b'], b: undefined, c: [] })
- ).toEqual('a=b')
+ it('avoids trailing &', () => {
+ expect(stringifyQuery({ a: 'a', b: undefined })).toEqual('a=a')
+ expect(stringifyQuery({ a: 'a', c: [] })).toEqual('a=a')
+ })
+
+ it('skips undefined in arrays', () => {
+ expect(stringifyQuery({ a: [undefined, '3'] })).toEqual('a=3')
+ expect(stringifyQuery({ a: [1, undefined, '3'] })).toEqual('a=1&a=3')
+ expect(stringifyQuery({ a: [1, undefined, '3', undefined] })).toEqual(
+ 'a=1&a=3'
+ )
})
it('stringifies arrays', () => {
import { decode, encodeQueryKey, encodeQueryValue, PLUS_RE } from './encoding'
/**
- * Possible values in normalized {@link LocationQuery}
+ * Possible values in normalized {@link LocationQuery}. `null` renders the query
+ * param but without an `=`: `?isNull&isEmpty=&other=other` -> `{ isNull: null,
+ * isEmpty: '', other: 'other' }`.
*
* @internal
*/
export type LocationQueryValue = string | null
/**
- * Possible values when defining a query
+ * Possible values when defining a query.
*
* @internal
*/
key = encodeQueryKey(key)
if (value == null) {
// only null adds the value
- if (value !== undefined) search += (search.length ? '&' : '') + key
+ if (value !== undefined) {
+ search += (search.length ? '&' : '') + key
+ }
continue
}
// keep null values
? value.map(v => v && encodeQueryValue(v))
: [value && encodeQueryValue(value)]
- for (let i = 0; i < values.length; i++) {
- if (values[i] === undefined) continue
- // only append & with non-empty search
- search += (search.length ? '&' : '') + key
- if (values[i] !== null) search += ('=' + values[i]) as string
- }
+ values.forEach(value => {
+ // skip undefined values in arrays as if they were not present
+ // smaller code than using filter
+ if (value !== undefined) {
+ // only append & with non-empty search
+ search += (search.length ? '&' : '') + key
+ if (value != null) search += '=' + value
+ }
+ })
}
return search