Skip to content

Instantly share code, notes, and snippets.

@copperwall
Last active March 18, 2018 17:46
Show Gist options
  • Save copperwall/322f3d0a3f8b8359f98d2fa60d939f17 to your computer and use it in GitHub Desktop.
Save copperwall/322f3d0a3f8b8359f98d2fa60d939f17 to your computer and use it in GitHub Desktop.
A array_map alternative for iterables
<?php
declare(strict_types = 1);
/**
* Like array_map() but over an iterable, and it returns a new iterable with
* mapping instead of a mapped array. The callable should take two arguments:
* a value to map and its key in the stream.
*/
function iterator_map(callable $cb, iterable $itr): iterable {
foreach ($itr as $key => $value) {
yield $cb($value, $key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment