jumpifbelow/php-functional-array

Classes to make array functional

4.0.0 2019-06-14 19:31 UTC

README

Development stage

The project is still in an early development phase. Even if all tests passed, based on the MDN documentation, it may be unreliable.

What's next?

It is mainly tested with integer-indexed array, starting from 0. While using an array this way is the most common case, some user may want to use with associative array. It should work, but it is not tested this way.

No BC should be done unless in major revision.

Another point is the global performance. It is actually built with one thing in mind: working. As an array could be used very intensively, some optimization may be necessary in future.

How to install it?

Just run Composer:

composer require jumpifbelow/php-functional-array

How to use it?

Two types of array are made.

The first, JumpIfBelow\Arrays\FluentArrayInterface is made to work like a PHP array, with all functions builtin directly in methods. All of the calls are immutable and fluent, meaning you can chain it without altering the first reference.

The second, JumpIfBelow\Arrays\JsArrayInterface is made to looks like a JS' array. Those familiar with JS will not be lost with this, except that an array in PHP could have string in key, non-contiguous integer or even negative integer.

Of course, the package comes with implementations you can already use like this:

<?php

use JumpIfBelow\Arrays\FluentArray;
use JumpIfBelow\Arrays\JsArray;

$a = new FluentArray([
    5,
    'er',
    'ert',
    'loop',
    false,
    null
]);

$newArray = $a
    ->filter(function ($x): bool {
        return is_string($x);
    })
    ->map(function (string $x): string {
        return strrev($x);
    })
    ->sort()
;

var_dump($newArray->toArray());

// those examples could be shortened because they are using defined functions
// note that the interface accepts any callable, which allow this writing

$newArray = $a
    ->filter('is_string')
    ->map('strrev')
    ->sort()
;

$a = new JsArray();
$a[] = 0;
$a[] = 'er';
$a[] = 4;
$a[] = 5.6;
$a[] = 1;

$newArray = $a
    ->filter(function ($value): bool {
        return is_int($value);
    })
    ->sort(function (int $a, int $b): int {
        return $a <=> $b;
    })
;

var_dump($newArray->length);
var_dump($newArray->toArray());

After the execution, the $a variable will still retain the same values as of the instantiation. $newArray will contains the filtered and then sorted array, which means it actually contains [0, 1, 4].