Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a tap function #95

Merged
merged 6 commits into from
Oct 11, 2023
Merged
Changes from 1 commit
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
32 changes: 32 additions & 0 deletions src/iter.php
Original file line number Diff line number Diff line change
Expand Up @@ -1257,6 +1257,38 @@ function toArrayWithKeys(iterable $iterable): array {
function isIterable($value) {
return is_array($value) || $value instanceof \Traversable;
}

/**
* Lazily performs a side effect for each value in an iterable.
*
* The passed function is called with the value and key of each element of the
* iterable. The return value of the function is ignored.
*
* Examples:
* $iterable = iter\range(1, 3);
* // => iterable(1, 2, 3)
*
* $iterable = iter\tap(function($value, $key) { echo $value; }, $iterable);
* // => iterable(1, 2, 3) : pending side effects
*
* iter\toArray($iterable);
* // => [1, 2, 3]
* // "123" : side effects were executed
*
* @template T
*
* @param callable(T):void $function A function to call for each value as a side effect
nikic marked this conversation as resolved.
Show resolved Hide resolved
* @param iterable<T> $iterable The iterable to tap
*
* @return iterable<T>
*/
function tap(callable $function, iterable $iterable): \Iterator {
foreach ($iterable as $key => $value) {
$function($value, $key);
yield $key => $value;
}
}

/*
* Python:
* compress()
Expand Down