| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Improved; |
||
| 6 | |||
| 7 | /** |
||
| 8 | * Filter to get only unique elements. |
||
| 9 | * |
||
| 10 | * @param iterable $iterable |
||
| 11 | * @param callable|null $serialize Callable function to serialize the value |
||
| 12 | * @return \Generator |
||
| 13 | */ |
||
| 14 | 9 | function iterable_unique(iterable $iterable, callable $serialize = null): \Generator |
|
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 15 | { |
||
| 16 | 8 | $fastMap = []; // entries as keys, entry must be a string |
|
| 17 | 8 | $slowMap = []; // non-string entries |
|
| 18 | |||
| 19 | 8 | foreach ($iterable as $key => $value) { |
|
| 20 | 7 | $entry = isset($serialize) ? call_user_func($serialize, $value, $key) : $value; |
|
| 21 | |||
| 22 | 7 | if (is_string($entry) ? isset($fastMap[$entry]) : in_array($entry, $slowMap, true)) { |
|
| 23 | 7 | continue; |
|
| 24 | } |
||
| 25 | |||
| 26 | 7 | if (is_string($entry)) { |
|
| 27 | 6 | $fastMap[$entry] = true; |
|
| 28 | } else { |
||
| 29 | 1 | $slowMap[] = $entry; |
|
| 30 | } |
||
| 31 | |||
| 32 | 7 | yield $key => $value; |
|
| 33 | } |
||
| 34 | } |
||
| 35 |