Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add path, path_or, prop, prop_or, props functions #187

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

win0err
Copy link
Contributor

@win0err win0err commented Jun 8, 2019

I'm happy to introduce the amazing set of functions: path, path_or, prop, prop_or, props.

Example:

<?php

use function Functional\map;
use function Functional\path_or;
use function Functional\prop;
use function Functional\prop_or;
use function Functional\props;
use function Functional\each;

include 'vendor/autoload.php';

$users = [
    ['first_name' => 'John', 'last_name' => 'Doe', 'birth' => 1969, 'languages' => ['js' => 5, 'php' => 10], 'os' => 'Ubuntu'],
    ['first_name' => 'Valerich', 'birth' => 1980],
    (object)['first_name' => 'John', 'last_name' => 'Appleseed', 'birth' => 1985, 'languages' => ['swift' => 15], 'os' => 'macOS'],
    ['first_name' => 'Taylor', 'last_name' => 'Otwell', 'birth' => 1986, 'languages' => ['php' => 12]],
];
$currentYear = (int) date('Y');

$developers = map(
    $users,
    function ($item) use ($currentYear) {
        return [
            'full_name' => implode(' ', props(['first_name', 'last_name'], $item)),
            'php_experience' => path_or(0, ['languages', 'php'], $item),
            'os' => prop_or('Fedora', 'os', $item),
            'age' => $currentYear - prop('birth', $item),
        ];
    }
);

each(
    $developers,
    function ($developer) {
        printf(
            "%s (%d y.o.), enjoys PHP for %d years\n",
            ...props(['full_name', 'age', 'php_experience'], $developer)
        );
    }
);

Result:

John Doe (50 y.o.), enjoys PHP for 10 years
Valerich (39 y.o.), enjoys PHP for 0 years
John Appleseed (34 y.o.), enjoys PHP for 0 years
Taylor Otwell (33 y.o.), enjoys PHP for 12 years

@lstrojny
Copy link
Owner

Thank you for the well done PR! Did you look into pick and pluck to compare what use cases aren’t supported?

@win0err
Copy link
Contributor Author

win0err commented Jun 11, 2019

Of course, I did!
pick — almost same as prop_or, but works only with arrays, but prop, prop_or, props also works with objects (that's why it's called props).
pluck — can be represented with the following code: map($list, fn($item) => prop($key, $item))

P.S. If you have any questions — feel free to ask.

Base automatically changed from master to main March 5, 2021 16:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants