search-query-parser icon indicating copy to clipboard operation
search-query-parser copied to clipboard

Add serialize function

Open punkpeye opened this issue 3 years ago • 1 comments

It would be nice to be able to re-build query using offsets.

punkpeye avatar Sep 28 '22 22:09 punkpeye

I tried implementing this but ran into a few limitations:

  • No way to tell if text is quoted
  • No way to tell what quotes text is using

This is what I've got so far:

type SearchParserOffset = (
  | SearchParserKeyWordOffset
  | SearchParserTextOffset
) & {
  offsetStart: number;
  offsetEnd: number;
};

type SearchParserKeyWordOffset = {
  keyword: string;
  value?: string;
};

type SearchParserTextOffset = {
  text: string;
};

export const serializeSearchQuery = (offsets: SearchParserOffset[]) => {
  let searchQuery = "";

  for (const offset of offsets) {
    const gapSize = offset.offsetStart - searchQuery.length;

    if (gapSize > 0) {
      searchQuery += Array.from({ length: gapSize }).fill(" ").join("");
    }

    if ("text" in offset) {
      if (offset.text.includes(" ")) {
        if (offset.text.includes(`'`) && !offset.text.includes(`"`)) {
          searchQuery += `"${offset.text}"`;
        } else {
          searchQuery += `'${offset.text.replaceAll(`'`, `\'`)}'`;
        }
      } else {
        searchQuery += offset.text;
      }
    } else {
      searchQuery += offset.keyword + ":" + offset.value;
    }
  }

  return searchQuery;
};

punkpeye avatar Sep 28 '22 22:09 punkpeye