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

Fluent arrays #11

@stancl

Description

@stancl

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);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions