crocodile2u / chainy

29 stars 3 forks source link

Support ReduceAssoc, MapAssoc with additional index/key argument #4

Closed Insolita closed 5 years ago

Insolita commented 5 years ago

it are not php native, but sometimes very usefull

it logic like as

public function array_reduce_assoc(iterable $array, $callback, $initial = [])
    {
        $acc = $initial;
        foreach ($array as $key => $value) {
            $acc = $callback($acc, $value, $key);
        }
        return $acc;
    }

public function array_map_assoc(iterable $array, $callback)
    {
        $result = [];
        foreach ($array as $key => $value) {
            $result[$key] = $callback($value, $key);
        }
        return $result;
    }
crocodile2u commented 5 years ago

Will think about it.

The code you provide for array_map_assoc() seems to contain an error (undefined variable $acc). Otherwise looks like a nice addition. I would come up with a different naming though.

Insolita commented 5 years ago

i type it from mobile, if u want i can make pr

crocodile2u commented 5 years ago

PRs are always welcome! Make sure you have a unit test though

On Mon, Nov 12, 2018, 17:03 Insolita notifications@github.com wrote:

i type it from mobile, if u want i can make pr

— You are receiving this because you commented.

Reply to this email directly, view it on GitHub https://github.com/crocodile2u/chainy/issues/4#issuecomment-437935040, or mute the thread https://github.com/notifications/unsubscribe-auth/ABqAdKcuMhCNWztuhpbPQHxHmdjKDTFKks5uuZvDgaJpZM4YZBEq .

-- Best regards, Victor Bolshov

crocodile2u commented 5 years ago

I decided not to introduce another map/reduce methods to Chain. Instead, I added an optional boolean $keys parameter to both Chain::map() and Chain::reduce(), which in essence work exactly as you described