mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-02-13 12:55:00 +00:00
45
packages/frontend/core/src/utils/fuzzy-match.ts
Normal file
45
packages/frontend/core/src/utils/fuzzy-match.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Checks if the name is a fuzzy match of the query.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const name = 'John Smith';
|
||||
* const query = 'js';
|
||||
* const isMatch = fuzzyMatch(name, query);
|
||||
* // isMatch: true
|
||||
* ```
|
||||
*
|
||||
* if initialMatch = true, the first char must match as well
|
||||
*/
|
||||
export function fuzzyMatch(
|
||||
name: string,
|
||||
query: string,
|
||||
matchInitial?: boolean
|
||||
) {
|
||||
const pureName = name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.split('')
|
||||
.filter(char => char !== ' ')
|
||||
.join('');
|
||||
|
||||
const regex = new RegExp(
|
||||
query
|
||||
.split('')
|
||||
.filter(char => char !== ' ')
|
||||
.map(item => `${escapeRegExp(item)}.*`)
|
||||
.join(''),
|
||||
'i'
|
||||
);
|
||||
|
||||
if (matchInitial && query.length > 0 && !pureName.startsWith(query[0])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return regex.test(pureName);
|
||||
}
|
||||
|
||||
function escapeRegExp(input: string) {
|
||||
// escape regex characters in the input string to prevent regex format errors
|
||||
return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
Reference in New Issue
Block a user