All files / urlsearchparams/src get.ts

100% Statements 16/16
83.33% Branches 5/6
100% Functions 6/6
100% Lines 13/13

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 33 34 35 36 37 38 39 40 41 421x 1x 1x         1x                                     5x     5x 1x 4x 1x   3x 3x 9x 5x        
import { pipe } from "@benneq/function";
import { filter, map } from "@benneq/iterable";
import { Entry, isUndefined } from "@benneq/object";
import {
  isString,
  stringPredicate,
  StringPredicateInput,
} from "@benneq/string";
 
/**
 * Returns all values from a {@link URLSearchParams} object matching the
 * `keyPredicate`.
 *
 * @example
 * ```ts
 * const getValues = get("k1");
 *
 * const urlSearchParams = new URLSearchParams([
 *   ["k1", "v1"],
 *   ["k2", "v2"],
 * ]);
 *
 * const values = getValues(urlSearchParams);
 * console.log(values); // ["v1"]
 * ```
 */
export const get = (
  keyPredicate?: StringPredicateInput
): ((urlSearchParams: URLSearchParams) => Iterable<string>) => {
  if (isUndefined(keyPredicate)) {
    return (urlSearchParams) => urlSearchParams.values();
  } else if (isString(keyPredicate)) {
    return (urlSearchParams) => urlSearchParams.getAll(keyPredicate) || [];
  } else {
    const predicate = stringPredicate(keyPredicate);
    return pipe(
      filter<Entry<string, string>>(([key]) => predicate(key)),
      map<Entry<string, string>, string>(([_key, value]) => value)
    );
  }
};