Skip to content

Commit

Permalink
feat(plugin-inquirer): add fuzzyFilter util Fuc provide cz-git
Browse files Browse the repository at this point in the history
link #22
  • Loading branch information
Zhengqbbb committed Apr 30, 2022
1 parent d78ce33 commit 83f773e
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/@cz-git/plugin-inquirer/src/shared/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from "./fuzzy";
export * from "./util";
export * from "./checkbox";
7 changes: 7 additions & 0 deletions packages/@cz-git/plugin-inquirer/src/shared/types/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface FilterArrayItemType {
value: string;
name: string;
emoji?: string;
index?: number;
score?: number;
}
42 changes: 42 additions & 0 deletions packages/@cz-git/plugin-inquirer/src/shared/utils/fuzzy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
* @license: MIT
*/

import type { FilterArrayItemType } from "../types";

/**
* @description: inputString match targetString return match score
* @param {string} input input string
Expand Down Expand Up @@ -44,3 +46,43 @@ export const fuzzyMatch = (

return null;
};

/**
* @description: Array fuzzy filter
* @param {string} input input string
* @param {Array<FilterArrayItemType | unknown>} arr target Array
* @return {Array<FilterArrayItemType>} filtered array
*/
export const fuzzyFilter = (
input: string,
arr: Array<FilterArrayItemType | unknown>,
targetKey: "name" | "value" = "name"
): Array<FilterArrayItemType> => {
if (!arr || !Array.isArray(arr) || arr.length === 0) {
return [];
} else if (typeof input !== "string" || input === "") {
return arr;
}

return arr
.reduce((preVal: Array<FilterArrayItemType>, 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;
}
});
};

0 comments on commit 83f773e

Please # to comment.