-
Notifications
You must be signed in to change notification settings - Fork 0
/
fix.comp.php
75 lines (65 loc) · 1.54 KB
/
fix.comp.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* Alias call_user_func_array to apply.
*/
function apply($callback, array $args) {
return call_user_func_array($callback, $args);
}
/**
* Returns the first item in an array.
*/
function first(array $arr) {
$copy = array_slice($arr, 0, 1, true);
return array_shift($copy);
}
/**
* Returns the last item in an array.
*/
function last(array $arr) {
$copy = array_slice($arr, 0, NULL, true);
return array_pop($copy);
}
/**
* Returns all but the last item in an array.
*/
function butlast(array $arr) {
$copy = array_slice($arr, 0, -1, true);
return $copy;
}
/**
* Sorts array and returns if sort result is true.
*/
function sorted($arr) {
$success = sort($arr);
return $success ? $arr : false;
}
/**
* Filter non-alpha strings from array of strings.
*/
function array_alpha($arr) {
return array_filter($arr, function($str) {
return ctype_alpha($str);
});
}
/**
* Takes a set of fns, returns new fn of variable args
* that applies the rightmost fn, and so on.
*/
function comp() {
$fns = func_get_args();
return function() use ($fns) {
$args = func_get_args();
$l = function($xs, $fns) use (&$l) {
if (empty($fns)) {
return first($xs);
}
$nextargs = apply(last($fns), $xs);
return $l(array($nextargs), butlast($fns));
};
return $l($args, $fns);
};
}
$all_chars = comp('trim', 'join', 'array_alpha', 'array_unique', 'sorted', 'str_split', 'strtolower');
$result = $all_chars('The quick brown fox jumps over the lazy dog.');
echo $result;
// abcdefghijklmnopqrstuvwxyz