Skip to content

Instantly share code, notes, and snippets.

@nrdmn
Created January 26, 2020 14:59
Show Gist options
  • Save nrdmn/140eba887530567dfa2def881ed84289 to your computer and use it in GitHub Desktop.
Save nrdmn/140eba887530567dfa2def881ed84289 to your computer and use it in GitHub Desktop.
/**
* Apply a function which produces an array to all of an array's elements and concatenate the results.
*
* @param callable $func The function to be applied to every of $arr's elements to produce a new array each.
* @param array $arr
* @return array
*/
function array_flatmap(callable $func, array $arr) : array
{
return array_merge([], ...array_map($func, $arr));
}
/**
* Create a list of all possible combinations of input arrays.
*
* Example:
* array_combinations(['a', 'b'], ['c', 'd']) == [['a', 'c'], ['a', 'd'], ['b', 'c'], ['b', 'd']]
*
* @param array ...$args
* @return array
*/
function array_combinations(array ...$args) : array
{
$array_combinations_ = function ($combinations, $args) use (&$array_combinations_) {
if (count($args) === 0) {
return $combinations;
} else {
return $array_combinations_(array_flatmap(function ($a) use ($combinations) {
return array_map(function ($b) use ($a) {
return array_merge($b, [$a]);
}, $combinations);
}, $args[0]), array_slice($args, 1));
}
};
if (count($args) === 0) {
return [];
} else {
return $array_combinations_([[]], $args);
}
}
/**
* Check if $needle is in array $haystack using a custom comparison function, $cmp.
*
* @param mixed $needle
* @param array $haystack
* @param callable $cmp
* @return bool
*/
function in_array_f($needle, array $haystack, callable $cmp) : bool
{
foreach ($haystack as $elem) {
if ($cmp($needle, $elem)) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment