All files / src/utils/search-query/translators translateAstToFreefind.ts

92.85% Statements 13/14
80% Branches 4/5
100% Functions 1/1
92.85% Lines 13/14

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    1x                                 1x 1x 6x 6x 4x 6x 1x 6x 1x 6x   6x 6x  
import type { SearchAst } from '../types';
 
/**
 * Translates a {@link SearchAst} into FreeFind's refined-search syntax (the
 * engine LiMac delegates to). Phrases are parenthesized so multi-word terms stay
 * grouped, and boolean nodes use FreeFind's `AND`/`OR`/`NOT` keywords.
 *
 * @category Utils
 * @group Converters
 * @param ast - The parsed query tree.
 * @returns A FreeFind query string.
 * @example
 * ```ts
 * translateAstToFreefind({ type: "or",
 *   left: { type: "term", value: "sulfuric acid", phrase: true },
 *   right: { type: "term", value: "boric acid", phrase: true } });
 * // "(sulfuric acid) OR (boric acid)"
 * ```
 * @source
 */
export function translateAstToFreefind(ast: SearchAst): string {
  switch (ast.type) {
    case 'term':
      return `(${ast.value})`;
    case 'and':
      return `${translateAstToFreefind(ast.left)} AND ${translateAstToFreefind(ast.right)}`;
    case 'or':
      return `${translateAstToFreefind(ast.left)} OR ${translateAstToFreefind(ast.right)}`;
    case 'not':
      return `NOT ${translateAstToFreefind(ast.operand)}`;
  }
}