loophp / collection

A (memory) friendly, easy, lazy and modular collection class.
https://loophp-collection.rtfd.io/
MIT License
721 stars 35 forks source link

Add `with` operation #271

Closed drupol closed 1 year ago

drupol commented 1 year ago

This PR:

Provide an easy way to extend the features of Collection. It a bit like the pipe operation, but instead of taking callable(s), it takes an instance of Operation. I guess working with classes and objects is better in PHP (which is not fully functional).

By providing the with operation, you allow anyone to plug-in any custom operation.

Minimal working example:

class AddAndMultiply extends AbstractOperation
{
    public function __invoke(): Closure
    {
        return static function (int $a, int $m) {
            return static function (ContractCollection $collection) use ($a, $m): Generator {
                foreach ($collection as $key => $value) {
                    yield $key => ($value + $a) * $m;
                }
            };
        };
    }
}

$c = Collection::unfold(static fn (int $a = 0, int $b = 1): array => [$b, $a + $b])
    ->limit(3)
    ->pluck(0)
    ->with((new AddAndMultiply()), [0, 2]);

print_r($c->all());

Follows #. Related to #. Fixes #.

what-the-diff[bot] commented 1 year ago
github-actions[bot] commented 1 year ago

Since this pull request has not had any activity within the last 5 days, I have marked it as stale. I will close it if no further activity occurs within the next 5 days.