-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.php
94 lines (83 loc) · 1.79 KB
/
functions.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
/**
* @template T
* @psalm-param iterable<T> $iterable
* @psalm-return array<array-key, T>
*/
function iterable_to_array($iterable): array {
if ($iterable instanceof Traversable) {
return iterator_to_array($iterable, true);
}
return $iterable;
}
/**
* @template T
* @psalm-param array<T> $data
*
* @psalm-return ?T
*/
function array_first(array $data) {
$key = array_key_first($data);
if (null === $key) {
return null;
}
return $data[$key];
}
/**
* @template T
*
* @psalm-param iterable<T> $items
* @psalm-param Closure(T):bool $callback
*
* @psalm-return T|null
*/
function find_first(iterable $items, Closure $closure) {
foreach ($items as $item) {
if ($closure($item)) {
return $item;
}
}
return null;
}
/**
* Improved array_map that works with iterables, with static analysis included.
*
* @template T
* @template R
*
* @psalm-param iterable<array-key, T> $input
* @psalm-param Closure(T, array-key):R $callback
*
* @psalm-return list<R>
*/
function array_map_i(iterable $input, Closure $callback): array {
$results = [];
foreach ($input as $key => $item) {
$results[] = $callback($item, $key);
}
return $results;
}
/**
* @template T
*
* @psalm-param iterable<array-key, T> $iterable
* @psalm-param Closure(array-key, T):void $callback
*/
function foreach_do(iterable $iterable, Closure $callback): void {
foreach ($iterable as $key => $value) {
$callback($key, $value);
}
}
/**
* @template T
*
* @psalm-param iterable<T> $iterable
* @psalm-param Closure(T):float $callback
*/
function array_sum_i(iterable $iterable, Closure $callback): float {
$sum = 0;
foreach ($iterable as $item) {
$sum += $callback($item);
}
return $sum;
}