All files / src/constants fuzzScorers.ts

100% Statements 30/30
100% Branches 2/2
100% Functions 1/1
100% Lines 30/30

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 751x                                                   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                       1x 1x 95x 95x  
import {
  partial_ratio,
  partial_token_set_ratio,
  partial_token_similarity_sort_ratio,
  partial_token_sort_ratio,
  ratio,
  token_set_ratio,
  token_similarity_sort_ratio,
  token_sort_ratio,
  WRatio,
} from 'fuzzball';
 
/**
 * Fuzz-match scorer registry shared between `SupplierBase.fuzzyFilter` and the
 * Advanced drawer section's override selector. Keys are stored in
 * `userSettings.fuzzScorerOverride`; when present at search time they replace
 * each supplier's per-class `fuzzScorer` default.
 *
 * `distance` is intentionally excluded — it's an edit distance (lower = more
 * similar), while all other scorers return 0–100 (higher = more similar), so
 * it doesn't plug into the same cutoff/filter flow.
 * @group Constants
 * @source
 */
export type FuzzScorerFn = (str1: string, str2: string) => number;
 
export const FUZZ_SCORERS = {
  ratio,
  partial_ratio,
  token_sort_ratio,
  token_set_ratio,
  token_similarity_sort_ratio,
  partial_token_sort_ratio,
  partial_token_set_ratio,
  partial_token_similarity_sort_ratio,
  WRatio,
} as const satisfies Record<string, FuzzScorerFn>;
 
export type FuzzScorerName = keyof typeof FUZZ_SCORERS;
 
/**
 * Ordered list of scorer names for UI option rendering. Kept as a tuple so the
 * select menu preserves the "simple → compound" visual ordering we use in the
 * comparison log.
 * @source
 */
export const FUZZ_SCORER_NAMES: readonly FuzzScorerName[] = [
  'ratio',
  'partial_ratio',
  'token_sort_ratio',
  'token_set_ratio',
  'token_similarity_sort_ratio',
  'partial_token_sort_ratio',
  'partial_token_set_ratio',
  'partial_token_similarity_sort_ratio',
  'WRatio',
];
 
/**
 * Type guard — narrows an arbitrary string (e.g. out of `userSettings`) to a
 * valid scorer key, so callers can safely index `FUZZ_SCORERS[name]`.
 * @param name - Candidate scorer name.
 * @returns True when `name` is a registered scorer.
 * @example
 * ```ts
 * if (isFuzzScorerName(userSettings.fuzzScorerOverride)) {
 *   const scorer = FUZZ_SCORERS[userSettings.fuzzScorerOverride];
 * }
 * ```
 * @source
 */
export function isFuzzScorerName(name: unknown): name is FuzzScorerName {
  return typeof name === 'string' && name in FUZZ_SCORERS;
}