Skip to content

Instantly share code, notes, and snippets.

@juniorbird
Last active June 21, 2016 23:01
Show Gist options
  • Save juniorbird/f66597cd84d2810f881c60dc433c69cb to your computer and use it in GitHub Desktop.
Save juniorbird/f66597cd84d2810f881c60dc433c69cb to your computer and use it in GitHub Desktop.
Composing functions in PHP
<?php
$sorted_arr = function ($range_to_sort) {
// Annoyingly, PHP can't return the sorted array from a sort
// Do it manually
usort($range_to_sort, function ($a, $b)
{
return($a[0] > $b[0]);
});
return $range_to_sort;
};
$merge_ranges = function ($sorted_range) {
return array_reduce($sorted_range, function ($accum, $event)
{
$len = count($accum) - 1;
if ($event[0] <= $accum[$len][1]) {
$start = $accum[$len][0];
if ($event[1] <= $accum[$len][1]) {
$end = $accum[$len][1];
} else {
$end = $event[1];
}
$accum[$len] = [$start, $end];
} else {
array_push($accum, $event);
}
return $accum;
}, [$sorted_range[0]]);
};
$range_hours = function ($merged_range) {
return array_reduce($merged_range, function($accum, $event)
{
array_push($accum, [$event[1] - $event[0]]);
return $accum;
}, []);
};
function compose(&$f, &$g) {
// Functions could be large, let's pass byRef
// We need to return a function
return function() use($f, $g) {
// When that new function is returned, arguments will be passed in
// use func_get_args so that we can compose functions with unknown #s of args
$args_in = func_get_args();
// Now call our functions!
return $g(call_user_func_array($f, $args_in));
};
};
$cal = [[3, 4], [9, 12], [1, 3], [6, 8], [9, 10]];
$f = compose($sorted_arr, $merge_ranges);
$hours_taken = compose($f, $range_hours);
print_r($hours_taken($cal)); // [3, 2, 3]
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment