All files / urlsearchparams/src fromMixedObject.ts

100% Statements 11/11
100% Branches 3/3
100% Functions 4/4
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 331x 1x                                     1x     1x 4x 1x 3x 2x   4x      
import { isArray } from "@benneq/array";
import { isString } from "@benneq/string";
 
/**
 * Parses a mixed object into {@link URLSearchParams}
 *
 * @example
 * Parse mixed object
 * ```ts
 * const mixedObject = {
 *   k1: "v1",
 *   k2: null
 * };
 *
 * const urlSearchParams = fromMixedObject(mixedObject);
 * console.log(urlSearchParams); // URLSearchParams([["k1", "v1"]])
 * ```
 *
 * @returns the parsed {@link URLSearchParams} object
 */
export const fromMixedObject = (
  obj: Record<string, string | string[] | null | undefined>
): URLSearchParams => {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    if (isString(value)) {
      acc.set(key, value);
    } else if (isArray(value)) {
      value.forEach((v) => acc.append(key, v));
    }
    return acc;
  }, new URLSearchParams());
};