Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion typed_stream/_impl/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import operator
import sys
import typing
from collections.abc import Callable, Iterable, Iterator, Mapping
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from numbers import Number, Real
from types import EllipsisType

Expand Down Expand Up @@ -965,6 +965,32 @@ def min(
raise exceptions.StreamEmptyError() from None
return self._finish(min_, close_source=True)

def multi_reduce(self, *funs: Callable[[T, T], T]) -> Sequence[T]:
"""Reduce the values of this stream with multiple functions.

>>> data = [1, 2, 3, 4, 5]
>>> sum_, count = Stream(data).multi_reduce(operator.add, lambda x, _: x + 1)
>>> sum_
15
>>> count
5
"""
iterator = iter(self._data)
try:
first_value = next(iterator)
except StopIteration:
raise exceptions.StreamEmptyError() from None

def multi_update(acc: list[T], value: T) -> list[T]:
for idx, fun in enumerate(funs):
acc[idx] = fun(acc[idx], value)
return acc

return self._finish(
functools.reduce(multi_update, iterator, [first_value] * len(funs)),
True,
)

@typing.overload
def nth(self, index: int, /) -> T: ... # noqa: D102

Expand Down