# All files / src matches.ts

100% Statements 13/13
100% Branches 15/15
100% Functions 3/3
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
    42
    43
    44
    45
    46
    47
    48
    49
    50

    2206x
    350x

    1856x
    1856x
    1769x
    1769x

    87x
    87x

    2205x
    3623x
    3623x
    3623x

    3623x

     export type NormalizerFn = (textToNormalize: string) => string;

    export type TextMatch = string | RegExp;
    export type TextMatchOptions = {
      exact?: boolean;
      normalizer?: NormalizerFn;
    };

    export function matches(
      matcher: TextMatch,
      text: string,
      normalizer: NormalizerFn = getDefaultNormalizer(),
      exact: boolean = true
    ): boolean {
      if (typeof text !== 'string') {
        return false;
      }

      const normalizedText = normalizer(text);
      if (typeof matcher === 'string') {
        const normalizedMatcher = normalizer(matcher);
        return exact
          ? normalizedText === normalizedMatcher
          : normalizedText.toLowerCase().includes(normalizedMatcher.toLowerCase());
      } else {
        // Reset state for global regexes: https://stackoverflow.com/a/1520839/484499
        matcher.lastIndex = 0;
        return matcher.test(normalizedText);
      }
    }

    type NormalizerConfig = {
      trim?: boolean;
      collapseWhitespace?: boolean;
    };

    export function getDefaultNormalizer({
      trim = true,
      collapseWhitespace = true,
    }: NormalizerConfig = {}): NormalizerFn {
      return (text: string) => {
        let normalizedText = text;
        normalizedText = trim ? normalizedText.trim() : normalizedText;
        normalizedText = collapseWhitespace
          ? normalizedText.replace(/\s+/g, ' ')
          : normalizedText;
        return normalizedText;
      };
    }