Skip to content
This repository has been archived by the owner on Sep 17, 2019. It is now read-only.

Fluent arrays #11

Open
stancl opened this issue Sep 16, 2019 · 0 comments
Open

Fluent arrays #11

stancl opened this issue Sep 16, 2019 · 0 comments

Comments

@stancl
Copy link

stancl commented Sep 16, 2019

Add a fluent array API:

[1, 2, 3]->map(function ($n) {
    return $n*2;
});

$odd = [1, 2, 3]->filter(function ($n) {
    return $n & 1;
});

$sum = [1, 2, 3]->reduce(function ($carry, $n) {
    return $carry + $n;
}, 0);


// chaining

$prices = $products->filter(function ($product) {
    return $product->category = 'foo';
})->map(function ($product) {
    return $product->price;
});

Implementation

-> calls to arrays could be wrapped in phpplus_arr(), which would return an instance of a class like this:

class PHPPlusArr
{
    /** @var array */
    public $array;

    public function __construct(array $array)
    {
       $this->array = $array;
    }

    public function toArray(): array
    {
        return $this->array;
    }

    public function map(callable $callback): self
    {
        return new static(array_map($callback, $this->array));
    }

    public function filter(callable $callback): self
    {
        return new static(array_filter($this->array, $callback));
    }

    public function reduce(callable $callback, $initial = null): self
    {
        return new static(array_reduce($this->array, $callback, $initial));
    }
}

Additionally, common methods like sum(), count(), etc can be made part of that class (as long as it doesn't grow to the size of Collection). An interesting solution, that would work for sum() and count() could be

public function __call($method, $args)
{
    return $method(...$args);
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant