# All files / searching useFuzzyMatch.ts

100% Statements 42/42
100% Branches 7/7
100% Functions 1/1
100% Lines 42/42

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
    431x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    4x
    4x
    4x
    4x
    10102x
    10102x
    34x
    34x
    10068x
    10102x
    3x
    3x
    3x
    10068x
    10068x
    4x
    4x
     "use client";
    import { useCallback, useRef } from "react";
    import { createFuzzyRegExp } from "./fuzzy.js";

    /**
     * @remarks \@since 6.0.0
     */
    export interface FuzzyMatchOptions {
      value: string;
      query: string;
    }

    /**
     * @remarks \@since 6.0.0
     */
    export type FuzzyMatch = (options: FuzzyMatchOptions) => boolean;

    /**
     * This hook implements a few optimizations for fuzzy searching and filtering
     * together for large datasets (10,000 or more items) and was really created
     * for the autocomplete component.
     *
     * @remarks \@since 6.0.0
     */
    export function useFuzzyMatch(): FuzzyMatch {
      const prevQuery = useRef("");
      const fuzzyRegExp = useRef<RegExp | null>(null);

      return useCallback((options: FuzzyMatchOptions) => {
        const { query, value } = options;
        if (!query) {
          return true;
        }

        if (!fuzzyRegExp.current || prevQuery.current !== query) {
          prevQuery.current = query;
          fuzzyRegExp.current = createFuzzyRegExp(query);
        }

        return value.length > 0 && fuzzyRegExp.current.test(value);
      }, []);
    }