From 83f773ed7561494d8f98fcb2cc316146ae90a29a Mon Sep 17 00:00:00 2001 From: Zhengqbbb <1074059947@qq.com> Date: Sat, 30 Apr 2022 15:08:04 +0800 Subject: [PATCH] feat(plugin-inquirer): add fuzzyFilter util Fuc provide cz-git link #22 --- .../plugin-inquirer/src/shared/types/index.ts | 2 +- .../plugin-inquirer/src/shared/types/util.ts | 7 ++++ .../plugin-inquirer/src/shared/utils/fuzzy.ts | 42 +++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 packages/@cz-git/plugin-inquirer/src/shared/types/util.ts diff --git a/packages/@cz-git/plugin-inquirer/src/shared/types/index.ts b/packages/@cz-git/plugin-inquirer/src/shared/types/index.ts index c2fbd7637..1392fb6b3 100644 --- a/packages/@cz-git/plugin-inquirer/src/shared/types/index.ts +++ b/packages/@cz-git/plugin-inquirer/src/shared/types/index.ts @@ -1,2 +1,2 @@ -export * from "./fuzzy"; +export * from "./util"; export * from "./checkbox"; diff --git a/packages/@cz-git/plugin-inquirer/src/shared/types/util.ts b/packages/@cz-git/plugin-inquirer/src/shared/types/util.ts new file mode 100644 index 000000000..be2abf6b1 --- /dev/null +++ b/packages/@cz-git/plugin-inquirer/src/shared/types/util.ts @@ -0,0 +1,7 @@ +export interface FilterArrayItemType { + value: string; + name: string; + emoji?: string; + index?: number; + score?: number; +} diff --git a/packages/@cz-git/plugin-inquirer/src/shared/utils/fuzzy.ts b/packages/@cz-git/plugin-inquirer/src/shared/utils/fuzzy.ts index 8d723daa3..b7c2a167d 100644 --- a/packages/@cz-git/plugin-inquirer/src/shared/utils/fuzzy.ts +++ b/packages/@cz-git/plugin-inquirer/src/shared/utils/fuzzy.ts @@ -4,6 +4,8 @@ * @license: MIT */ +import type { FilterArrayItemType } from "../types"; + /** * @description: inputString match targetString return match score * @param {string} input input string @@ -44,3 +46,43 @@ export const fuzzyMatch = ( return null; }; + +/** + * @description: Array fuzzy filter + * @param {string} input input string + * @param {Array} arr target Array + * @return {Array} filtered array + */ +export const fuzzyFilter = ( + input: string, + arr: Array, + targetKey: "name" | "value" = "name" +): Array => { + if (!arr || !Array.isArray(arr) || arr.length === 0) { + return []; + } else if (typeof input !== "string" || input === "") { + return arr; + } + + return arr + .reduce((preVal: Array, curItem: FilterArrayItemType, index) => { + if (!curItem || !curItem[targetKey]) return preVal; + const score = fuzzyMatch(input, curItem[targetKey]); + if (score !== null) { + preVal.push({ + score, + index, + ...curItem + }); + } + return preVal; + }, []) + .sort((a: any, b: any) => { + const compare = b.score - a.score; + if (compare) { + return compare; + } else { + return a.index - b.index; + } + }); +};