search<T> static method
- required Iterable<
T> items, - required dynamic searchTerms,
- SearchOnFunction<
T> ? searchOn, - int levenshteinDistance = 0,
- bool ignoreCase = true,
- bool ignoreDiacritics = true,
- bool ignoreWordSplitters = true,
- bool splitCamelCase = true,
- bool useWildcards = false,
- bool allIfEmpty = true,
- int maxResults = 0,
- int minChars = 0,
Searches the iterable for items that match the specified search criteria.
- The
searchTerms
parameter specifies the term to search for. Can be a string or a list of strings. - The
searchOn
parameter is a function that returns a list of strings to search on for each item. - The
levenshteinDistance
parameter specifies the maximum Levenshtein distance allowed for fuzzy matching. - The
ignoreCase
,ignoreDiacritics
,ignoreWordSplitters
,splitCamelCase
,useWildcards
, andallIfEmpty
parameters control various search options.
Returns an iterable of items that match the search criteria, ordered by relevance. The relevance is determined by the number of matches and the Levenshtein distance (if applicable).
Implementation
static Iterable<T> search<T>({
required Iterable<T> items,
required dynamic searchTerms,
SearchOnFunction<T>? searchOn,
int levenshteinDistance = 0,
bool ignoreCase = true,
bool ignoreDiacritics = true,
bool ignoreWordSplitters = true,
bool splitCamelCase = true,
bool useWildcards = false,
bool allIfEmpty = true,
int maxResults = 0,
int minChars = 0,
}) {
if (items.isEmpty) return <T>[].orderBy((e) => true);
var searches = forceRecursiveList(searchTerms).whereNotBlank;
if (minChars > 0) {
searches = searches.where((e) => flatString(e).length >= minChars);
allIfEmpty = false;
}
if (searches.isEmpty) {
if (allIfEmpty) {
return items;
} else {
return <T>[];
}
}
searchOn ??= (T item) => [changeTo<string>(item)];
var l = [
...items.where(
(item) {
return searchFunction(
searchTerms: searches,
searchOnItems: searchOn!(item),
ignoreCase: ignoreCase,
ignoreDiacritics: ignoreDiacritics,
ignoreWordSplitters: ignoreWordSplitters,
splitCamelCase: splitCamelCase,
useWildcards: useWildcards,
levenshteinDistance: levenshteinDistance,
);
},
)
];
if (l.isEmpty && levenshteinDistance > 0) {
l = [
...items.where(
(item) => levenshteinFunction(
searchTerms: searches,
searchOnItems: searchOn!(item),
levenshteinDistance: levenshteinDistance,
ignoreCase: ignoreCase,
),
)
];
}
l = [
...l.orderByDescending(
(item) => countJaro(
searchTerms: searches,
searchOn: searchOn!(item),
ignoreCase: ignoreCase,
ignoreDiacritics: ignoreDiacritics,
ignoreWordSplitters: ignoreWordSplitters,
splitCamelCase: splitCamelCase,
),
),
];
if (maxResults > 0) l = [...l.take(maxResults)];
return l;
}