Skip to content
This repository has been archived by the owner on Jul 6, 2019. It is now read-only.

Provide array keys to predicates in array methods #85

Open
carlwiedemann opened this issue Dec 29, 2015 · 0 comments
Open

Provide array keys to predicates in array methods #85

carlwiedemann opened this issue Dec 29, 2015 · 0 comments

Comments

@carlwiedemann
Copy link

Just started investigating this project.

One of my biggest complaints about PHP's native methods array_map(), array_filter(), array_reduce() is that they only provide the array value to the predicate Closure instead of both the key and the value as Underscore.js does.

It would be really helpful if this library provided those.

I've read that there's intent not to collide native method names, i.e. using each instead of map, so I'd suggest select instead of filter and fold instead of reduce for these revised functions.

Consider:

// Map (aka each) example.
// Returns ['a' => 'happy dog', 'b' => 'sad elephant', 'c' => 'happy frog']
Arrays::each(['a' => 'dog', 'b' => 'elephant', 'c' => 'frog'], function ($value, $key) {
  $mood = $key == 'b' ? 'sad' : 'happy';
  return sprintf('%s %s', $mood, $value);
});
// Reduce (aka fold) example.
// Returns ['Cat A', 'Cat C']
Arrays::fold(['Cat A' => 'XY', 'Cat B' => 'XX', 'Cat C' => 'XY'], function ($carry, $value, $key) {
  return $value == 'XY' ? $carry + $key : $carry;
}, []);
// Filter (aka select) example.
// Returns ['b', 'd', 'f']
Arrays::select(['a', 'b', 'c', 'd', 'e', 'f'], function ($value, $key) {
  return $key % 2 == 1;
});

Unless there is disagreement with the proposed changes I'll seek to contribute these.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant