|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Smoren\Sequence\Functions; |
|
4
|
|
|
|
|
5
|
|
|
use Smoren\Sequence\Structs\IndexedArray; |
|
6
|
|
|
use Smoren\Sequence\Structs\Range; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Creates iterable range. |
|
10
|
|
|
* |
|
11
|
|
|
* @param int $start start value |
|
12
|
|
|
* @param int<0, max>|null $size size of elements |
|
13
|
|
|
* @param int $step range step |
|
14
|
|
|
* |
|
15
|
|
|
* @return Range<int> iterable range |
|
16
|
|
|
*/ |
|
17
|
|
|
function xrange(int $start, ?int $size = null, int $step = 1): Range |
|
18
|
|
|
{ |
|
19
|
9 |
|
if($size === null) { |
|
20
|
2 |
|
[$start, $size] = [0, $start]; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
9 |
|
return new Range($start, $size, $step); |
|
|
|
|
|
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Maps iterable collection and returns IndexedArray of mapped values. |
|
28
|
|
|
* |
|
29
|
|
|
* @template TInput |
|
30
|
|
|
* @template TOutput |
|
31
|
|
|
* |
|
32
|
|
|
* @param iterable<TInput> $collection |
|
33
|
|
|
* @param callable(TInput $item): TOutput $mapper |
|
34
|
|
|
* |
|
35
|
|
|
* @return IndexedArray<TOutput> |
|
36
|
|
|
*/ |
|
37
|
|
|
function map(iterable $collection, callable $mapper): IndexedArray |
|
38
|
|
|
{ |
|
39
|
5 |
|
$result = new IndexedArray(); |
|
40
|
|
|
|
|
41
|
5 |
|
foreach($collection as $item) { |
|
42
|
4 |
|
$result[] = $mapper($item); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
5 |
|
return $result; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* Filters iterable collection and returns IndexedArray of filtered items. |
|
50
|
|
|
* |
|
51
|
|
|
* @template T |
|
52
|
|
|
* |
|
53
|
|
|
* @param iterable<T> $collection |
|
54
|
|
|
* @param callable(T $item): T $filter |
|
55
|
|
|
* |
|
56
|
|
|
* @return IndexedArray<T> |
|
57
|
|
|
*/ |
|
58
|
|
|
function filter(iterable $collection, callable $filter): IndexedArray |
|
59
|
|
|
{ |
|
60
|
6 |
|
$result = new IndexedArray(); |
|
61
|
|
|
|
|
62
|
6 |
|
foreach($collection as $item) { |
|
63
|
5 |
|
if($filter($item)) { |
|
64
|
4 |
|
$result[] = $item; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
6 |
|
return $result; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Reduces iterable collection. |
|
73
|
|
|
* |
|
74
|
|
|
* @template TInput |
|
75
|
|
|
* @template TOutput |
|
76
|
|
|
* |
|
77
|
|
|
* @param iterable<TInput> $collection |
|
78
|
|
|
* @param callable(TOutput|null $carry, TInput $item): TOutput $reducer |
|
79
|
|
|
* @param TOutput|null $initialValue |
|
|
|
|
|
|
80
|
|
|
* |
|
81
|
|
|
* @return TOutput|null |
|
82
|
|
|
*/ |
|
83
|
|
|
function reduce(iterable $collection, callable $reducer, $initialValue = null) |
|
84
|
|
|
{ |
|
85
|
6 |
|
$carry = $initialValue; |
|
86
|
|
|
|
|
87
|
6 |
|
foreach($collection as $item) { |
|
88
|
4 |
|
$carry = $reducer($carry, $item); |
|
89
|
|
|
} |
|
90
|
|
|
|
|
91
|
6 |
|
return $carry; |
|
92
|
|
|
} |
|
93
|
|
|
|