from typing import Any, Callable, Dict, Iterable, List from server.utils.mappers.core.getters import getter def _prepare_search(search: str = "", delimiter: str = ",") -> List[str]: """Split searched string to a list of strings Args: search: str delimiter: words delimiter in a "search" str to replace """ return search.lower().replace(delimiter, " ").split() if search.find(",") > 0 else [search.lower()] def _check_search(look_for: List[str], search_in: str) -> bool: """Check if searched words are present in a string we are searching Args: look_for: List of words to look for search_in: string to be searched in Returns: boolean that describes presence of a search in a searched string """ return all(list(map(lambda item: item in (search_in or "").lower(), look_for))) def check_item_by_search(item: Dict[str, Any], search_in: Iterable[str], search: str, occurrence: Callable = any): """Check if search is present in single item["search_in"] value. Args: item: Dicts to check search in search_in: path to a value in a single item -> supports . delimiter -> ex: "playlists.name" supports multiple paths search: value or values divided by comma that will be searched in a value we get from item by search_in path occurrence: builtin function - one of [all, any] that describes occurrence of each "search" value in a value we got from item by a "search_in" path """ return occurrence( list( map( lambda i: _check_search(_prepare_search(search), getter(item, key=i, none_result="").lower()), search_in ) ) ) def get_search(items: List[Dict[str, Any]], search_in: Iterable[str], search: str, occurrence: Callable = all): """Filter items by search Args: items: List of Dicts to check search in search_in: path to a value in a single item -> supports . delimiter -> ex: "playlists.name" search: value or values divided by comma that will be searched in a value we get from item by search_in path occurrence: builtin function - one of [all, any] that describes occurrence of each "search" value in a value we got from item by a "search_in" path """ return list(filter(lambda item: check_item_by_search(item, search_in, search, occurrence), items))