Source code for ska_mid_cbf_fhs_common.helpers.functional

from collections.abc import Callable, Iterable
from typing import TypeVar

T = TypeVar("T")


[docs] def find(func: Callable[[T], bool], iterable: Iterable[T]) -> T | None: """Find the first element in the iterable for which the specified function returns True. Args: func (:obj:`Callable[[T], bool]`): The function to run against each element in the iterable. iterable (:obj:`Iterable[T]`): The iterable to check. Returns: :obj:`T | None`: The first element in the iterable for which the specified function returns True, or None if no matching element was found. """ try: return next(filter(func, iterable)) except StopIteration: return None
[docs] def find_index(func: Callable[[T], bool], iterable: Iterable[T]) -> int | None: """Find the index of the first element in the iterable for which the specified function returns True. Args: func (:obj:`Callable[[T], bool]`): The function to run against each element in the iterable. iterable (:obj:`Iterable[T]`): The iterable to check. Returns: :obj:`int`: The index of the first element in the iterable for which the specified function returns True, or None if no matching element was found. """ try: return next(filter(lambda pair: func(pair[1]), enumerate(iterable)))[0] except StopIteration: return None