All files / typeahead si-typeahead.sorting.ts

100% Statements 10/10
85% Branches 17/20
100% Functions 4/4
100% Lines 10/10

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                              438x 396x 2x   394x 12x   382x           382x               382x 15x   367x        
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { TypeaheadMatch } from './si-typeahead.model';
 
export class SiTypeaheadSorting {
  sortMatches(matches: TypeaheadMatch[]): TypeaheadMatch[] {
    // Sort the matches,
    // first is the option and query an exact match.
    // then according to whether it is matching in the beginning,
    // then whether it matches the entire untokenized query.
    // then according to how many unique separate matches it contains.
    // then according to how many unique matches it contains.
    // then according to how many matches it contains.
    return matches.sort((matchA, matchB) => {
      if (matchA.stringMatch || matchB.stringMatch) {
        return matchA.stringMatch ? -1 : 1;
      }
      if (matchA.atBeginning) {
        return !matchB.atBeginning ? -1 : this.compareMatches(matchA, matchB);
      } else {
        return matchB.atBeginning ? 1 : this.compareMatches(matchA, matchB);
      }
    });
  }
 
  private compareMatchesNumbers(matchA: TypeaheadMatch, matchB: TypeaheadMatch): number {
    return (
      matchB.uniqueSeparateMatches - matchA.uniqueSeparateMatches ||
      matchB.uniqueMatches - matchA.uniqueMatches ||
      matchB.matches - matchA.matches
    );
  }
 
  private compareMatches(matchA: TypeaheadMatch, matchB: TypeaheadMatch): number {
    if (matchA.matchesEntireQuery) {
      return !matchB.matchesEntireQuery ? -1 : this.compareMatchesNumbers(matchA, matchB);
    } else {
      return matchB.matchesEntireQuery ? 1 : this.compareMatchesNumbers(matchA, matchB);
    }
  }
}