Skip to content

Commit

Permalink
feat: Add Squash operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed May 15, 2021
1 parent df76d3d commit a10e2ab
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
use loophp\collection\Operation\Sort;
use loophp\collection\Operation\Span;
use loophp\collection\Operation\Split;
use loophp\collection\Operation\Squash;
use loophp\collection\Operation\Tail;
use loophp\collection\Operation\Tails;
use loophp\collection\Operation\TakeWhile;
Expand Down Expand Up @@ -712,6 +713,11 @@ public function split(int $type = Operation\Splitable::BEFORE, callable ...$call
return new self(Split::of()($type)(...$callbacks), $this->getIterator());
}

public function squash(bool $throwOnException = true): CollectionInterface
{
return new self(Squash::of()($throwOnException)($this->getIterator()), $this->getIterator());
}

public function tail(): CollectionInterface
{
return new self(Tail::of(), $this->getIterator());
Expand Down
72 changes: 72 additions & 0 deletions src/Operation/Squash.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

/**
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

declare(strict_types=1);

namespace loophp\collection\Operation;

use Closure;
use Generator;
use Iterator;
use Throwable;

/**
* @psalm-template TKey
* @psalm-template TKey of array-key
* @psalm-template T
*/
final class Squash extends AbstractOperation
{
/**
* @psalm-return Closure(bool): Closure(Iterator<TKey, T>): Closure(Iterator<TKey, T>): Iterator<TKey, T>
*/
public function __invoke(): Closure
{
return
/**
* @psalm-return Closure(Iterator<TKey, T>): Closure(Iterator<TKey, T>): Iterator<TKey, T>
*/
static function (bool $throwOnException): Closure {
return
/**
* @psalm-param Iterator<TKey, T> $iterator
*
* @psalm-return Closure(Iterator<TKey, T>): Generator<TKey, T>
*/
static function (Iterator $iterator) use ($throwOnException): Closure {
// As keys can be of any type in this library.We cannot use
// iterator_to_array() because it expect keys to be int|string.
try {
foreach ($iterator as $key => $value) {
}
} catch (Throwable $e) {
if (true === $throwOnException) {
throw $e;
}
}

return
/**
* @psalm-param Iterator<TKey, T> $iterator
*
* @psalm-return Generator<TKey, T>
*/
static function (Iterator $iterator) use ($throwOnException): Generator {
try {
foreach ($iterator as $key => $value) {
yield $key => $value;
}
} catch (Throwable $e) {
if (true === $throwOnException) {
throw $e;
}
}
};
};
};
}
}

0 comments on commit a10e2ab

Please sign in to comment.