Last active
July 28, 2016 14:21
-
-
Save slifin/01ad77983cc4e559fc0667c88c227a6b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class _ {} | |
| function compose(callable $fn, ...$start) { | |
| return pipe($fn, ...array_reverse($start)); | |
| } | |
| function filter(callable $fn, $data) { | |
| return array_filter((array)$data, function ($v, $k) use ($fn, $data) { | |
| return $fn($v, $k, $data); | |
| }, ARRAY_FILTER_USE_BOTH); | |
| } | |
| function get($data, array $offsets, $default, $lens = 'prop') { | |
| $results = call_user_func(call_user_func_array('pipe', array_map(function($offset) { | |
| return partial($prop, (new _), $offset); | |
| },$offsets)), $data); | |
| return is_a($results, '_') ? $default : $results; | |
| } | |
| function map(callable $fn, ...$data) { | |
| return array_map(function ($val, $key) use ($fn, $data) { | |
| return $fn($val, $key, ...$data); | |
| }, (array)$first, array_keys((array)$first)); | |
| } | |
| function partial(callable $fn, ...$start) { | |
| return function (...$args) use ($fn, $start) { | |
| return @$fn(...array_map(function ($v) use (&$args) { | |
| return is_a($v, '_') ? array_shift($args) : $v; | |
| }, $start)); | |
| }; | |
| } | |
| function pipe(callable $fn, ...$fns) { | |
| return function(...$args) use($fns, $fn) { | |
| return array_reduce($fns, function($carry, $f) { | |
| return $f($carry); | |
| }, $fn(...$args)); | |
| }; | |
| } | |
| function prop($data, $prop) { | |
| $test = (array)$data; | |
| if (isset($test[$prop])) | |
| return $test[$prop]; | |
| return (new _); | |
| } | |
| function reduce(callable $fn, $data, $init = null) { | |
| return array_reduce(array_keys((array)$data), function ($carry, $key) use ($fn, $data) { | |
| return $fn($carry, $data[$key], $key, $data); | |
| }, $init); | |
| } | |
| function recursive_array_filter($array, $callback, $flag = RecursiveIteratorIterator::SELF_FIRST) { | |
| return iterator_to_array(new CallbackFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($array), $flag), $callback), FALSE); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment