@grafana/ui
Version:
Grafana Components Library
1 lines • 3.38 kB
Source Map (JSON)
{"version":3,"file":"fuzzy.mjs","sources":["../../../src/utils/fuzzy.ts"],"sourcesContent":["import { last } from 'lodash';\n\nimport { HighlightPart } from '../types/completion';\n\ntype FuzzyMatch = {\n /**\n * Total number of unmatched letters between matched letters\n */\n distance: number;\n ranges: HighlightPart[];\n found: boolean;\n};\n\n/**\n * Attempts to do a partial input search, e.g. allowing to search for a text (needle)\n * in another text (stack) by skipping some letters in-between. All letters from\n * the needle must exist in the stack in the same order to find a match.\n *\n * The search is case sensitive. Convert stack and needle to lower case\n * to make it case insensitive.\n *\n * @param stack - main text to be searched\n * @param needle - partial text to find in the stack\n *\n * @internal\n */\nexport function fuzzyMatch(stack: string, needle: string): FuzzyMatch {\n let distance = 0,\n searchIndex = stack.indexOf(needle);\n // Remove whitespace from needle as a temporary solution to treat separate string\n // queries as 'AND'\n needle = needle.replace(/\\s/g, '');\n\n const ranges: HighlightPart[] = [];\n\n if (searchIndex !== -1) {\n return {\n distance: 0,\n found: true,\n ranges: [{ start: searchIndex, end: searchIndex + needle.length - 1 }],\n };\n }\n\n for (const letter of needle) {\n const letterIndex = stack.indexOf(letter, searchIndex);\n\n if (letterIndex === -1) {\n return { distance: Infinity, ranges: [], found: false };\n }\n // do not cumulate the distance if it's the first letter\n if (searchIndex !== -1) {\n distance += letterIndex - searchIndex;\n }\n searchIndex = letterIndex + 1;\n\n if (ranges.length === 0) {\n ranges.push({ start: letterIndex, end: letterIndex });\n } else {\n const lastRange = last(ranges)!;\n if (letterIndex === lastRange.end + 1) {\n lastRange.end++;\n } else {\n ranges.push({ start: letterIndex, end: letterIndex });\n }\n }\n }\n\n return {\n distance: distance,\n ranges,\n found: true,\n };\n}\n"],"names":[],"mappings":";;;AA0BO,SAAS,UAAA,CAAW,OAAe,MAAA,EAA4B;AACpE,EAAA,IAAI,QAAA,GAAW,CAAA,EACb,WAAA,GAAc,KAAA,CAAM,QAAQ,MAAM,CAAA;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