# All files / searching utils.ts

100% Statements 53/53
100% Branches 14/14
100% Functions 2/2
100% Lines 53/53

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
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    541x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    34x
    100165x
    100162x
    100162x
    3x
    3x
    3x
    3x
    3x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    37x
    37x
    37x
    37x
    37x
    5x
    5x
    32x
    32x
    37x
    2x
    2x
    30x
    37x
    37x
    100177x
    37x
    37x
     import { type TextExtractor } from "../types.js";
    import { toSearchQuery } from "./toSearchQuery.js";
    import { type BaseSearchOptions } from "./types.js";

    /**
     * @remarks \@since 6.0.0
     * @internal
     */
    export const defaultExtractor =
      <T>(name: string) =>
      (item: T): string => {
        if (typeof item === "string") {
          return item;
        }

        throw new Error(
          `A \`TextExtractor\` must be provided to \`${name}\` for lists that do not contain strings`
        );
      };

    /**
     * @internal
     * @remarks \@since 6.0.0
     */
    export interface SearchOptions<T> extends BaseSearchOptions<T> {
      type: "search" | "filter";
      filter(query: string, value: string): boolean;
      extractor: TextExtractor<T>;
    }

    /**
     * @internal
     * @remarks \@since 6.0.0
     */
    export function search<T>(
      options: SearchOptions<T>
    ): readonly T[] | T | undefined {
      const { list, type, query, filter, extractor, whitespace = "keep" } = options;
      const fallback = type === "search" ? undefined : list;
      if (!list.length) {
        return fallback;
      }

      const q = toSearchQuery(query, whitespace);
      if (!q) {
        return fallback;
      }

      const fn = type === "search" ? "find" : "filter";
      return list[fn]((item) =>
        filter(q, toSearchQuery(extractor(item), whitespace))
      );
    }