Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active June 6, 2021 14:37
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/4ef61fd5c0a35e5aa8fc699febb86487 to your computer and use it in GitHub Desktop.
Save mindplay-dk/4ef61fd5c0a35e5aa8fc699febb86487 to your computer and use it in GitHub Desktop.
Linear collection workflow

You can have a linear workflow with the array functions.

The following is unreadable:

$output = array_reduce(
  array_map(
    function($n) { return $n ** 2; }
    array_filter($input, function($n) { return $n % 2 == 0; })
  ),
  function($x, $y) { return $x + $y; }
);

To get a more linear workflow, don't reinvent the wheel or introduce new dependencies. Just stick to idiomatic PHP and introduce an intermediary variable:

$output = $input;
$output = array_filter($output, function($n) { return $n % 2 == 0; });
$output = array_map(function($n) { return $n ** 2; }, $output);
$output = array_reduce($output, function($x, $y) { return $x + $y; });

Note that I'm copying $input to $output for two reasons:

  1. Avoid overwriting $input (which can be helpful for debugging etc.)
  2. Allows you to freely rearrange all operations on the collection $output by simply moving the lines up or down.

This linear workflow also is easier to debug - stepping line-by-line in a debugger will reveal the state of the array after each operation, without having to drill through any call-stacks etc.

@alexlvcom
Copy link

Completely agree

@haampie
Copy link

haampie commented Apr 7, 2017

In fact I think it wouldn't make sense to have a map & reduce method on the collection itself, because they map to a different type. In Haskell for instance the type of map is (a -> b) -> [a] -> [b]: a collection of a's is mapped to a collection of b's. In PHP you can't specialize a collection easily, but clearly if you'd map an array [User] to an array [string], I would argue a simple free function should do the trick. Same story for reduce.

Methods that return a view of the collection (filter, take) could maybe be part of such a collection class.

@radmen
Copy link

radmen commented May 29, 2017

Years ago I was frustrated about this inconsistency so I've tried to write my own implementation of array chains. It works (or at least worked) automatically by guessing proper function name and place in list of arguments. https://github.com/radmen/ArrayChain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment