11import { escapeStringRegexp } from '@weapp-core/regex'
22
33export type NameMatcher = ( value : string ) => boolean
4+ const NEVER_MATCH_NAME : NameMatcher = ( ) => false
5+ const GLOBAL_FLAG_REGEXP = / g / g
46
57function buildFuzzyMatcher ( fuzzyStrings : string [ ] ) : ( ( value : string ) => boolean ) | undefined {
68 if ( fuzzyStrings . length === 0 ) {
@@ -20,15 +22,15 @@ function normaliseRegex(regex: RegExp) {
2022 if ( ! flags . includes ( 'g' ) ) {
2123 return regex
2224 }
23- return new RegExp ( source , flags . replace ( / g / g , '' ) )
25+ return new RegExp ( source , flags . replace ( GLOBAL_FLAG_REGEXP , '' ) )
2426}
2527
2628export function createNameMatcher (
2729 list : ( string | RegExp ) [ ] | undefined ,
2830 { exact = false } : { exact ?: boolean } = { } ,
2931) : NameMatcher {
3032 if ( ! list || list . length === 0 ) {
31- return ( ) => false
33+ return NEVER_MATCH_NAME
3234 }
3335
3436 const exactStrings = exact ? new Set < string > ( ) : undefined
@@ -49,13 +51,43 @@ export function createNameMatcher(
4951 }
5052 }
5153
54+ if ( exact ) {
55+ const exactStringCount = exactStrings ?. size ?? 0
56+ if ( exactStringCount === 1 && regexList . length === 0 ) {
57+ const [ needle ] = exactStrings !
58+ return value => value === needle
59+ }
60+
61+ if ( regexList . length === 0 ) {
62+ return value => exactStrings ! . has ( value )
63+ }
64+
65+ if ( exactStringCount === 0 && regexList . length === 1 ) {
66+ const [ regex ] = regexList
67+ return value => regex . test ( value )
68+ }
69+
70+ return ( value : string ) => {
71+ if ( exactStrings ?. has ( value ) ) {
72+ return true
73+ }
74+ return regexList . some ( regex => regex . test ( value ) )
75+ }
76+ }
77+
5278 const fuzzyMatcher = exact ? undefined : buildFuzzyMatcher ( fuzzyStrings )
5379 const hasRegex = regexList . length > 0
5480
81+ if ( fuzzyMatcher && ! hasRegex ) {
82+ return fuzzyMatcher
83+ }
84+
85+ if ( ! fuzzyMatcher && regexList . length === 1 ) {
86+ const [ regex ] = regexList
87+ return value => regex . test ( value )
88+ }
89+
5590 return ( value : string ) => {
56- if ( exact && exactStrings ?. has ( value ) ) {
57- return true
58- }
5991 if ( fuzzyMatcher ?.( value ) ) {
6092 return true
6193 }
0 commit comments