crocodile2u/chainy

Support ReduceAssoc, MapAssoc with additional index/key argument

Insolita opened this issue · 4 comments

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

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.

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

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