|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Smoren\Sequence\Structs; |
|
4
|
|
|
|
|
5
|
|
|
use function Smoren\Sequence\Functions\reduce; |
|
6
|
|
|
use function Smoren\Sequence\Functions\xrange; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Implementation of sequence configured with callables. |
|
10
|
|
|
* |
|
11
|
|
|
* @template T |
|
12
|
|
|
* @extends Sequence<T> |
|
13
|
|
|
*/ |
|
14
|
|
|
class DynamicSequence extends Sequence |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var callable(T $previousValue): T getter for the next value |
|
18
|
|
|
*/ |
|
19
|
|
|
protected $nextValueGetter; |
|
20
|
|
|
/** |
|
21
|
|
|
* @var (callable(int $index, T $start): T)|null getter for the i-th value |
|
|
|
|
|
|
22
|
|
|
*/ |
|
23
|
|
|
protected $indexValueGetter; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* StepSequence constructor. |
|
27
|
|
|
* |
|
28
|
|
|
* @param T $start start of the sequence |
|
29
|
|
|
* @param int<0, max>|null $size size of the sequence (infinite if null) |
|
30
|
|
|
* @param callable(T $previousValue): T $nextValueGetter getter for the next value |
|
31
|
|
|
* @param (callable(int $index, T $start): T)|null $indexValueGetter getter for the i-th value |
|
|
|
|
|
|
32
|
|
|
*/ |
|
33
|
8 |
|
public function __construct( |
|
34
|
|
|
$start, |
|
35
|
|
|
?int $size, |
|
36
|
|
|
callable $nextValueGetter, |
|
37
|
|
|
?callable $indexValueGetter = null |
|
38
|
|
|
) { |
|
39
|
8 |
|
parent::__construct($start, $size); |
|
40
|
8 |
|
$this->nextValueGetter = $nextValueGetter; |
|
41
|
8 |
|
$this->indexValueGetter = $indexValueGetter; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* {@inheritDoc} |
|
46
|
|
|
*/ |
|
47
|
8 |
|
public function getNextValue($previousValue) |
|
48
|
|
|
{ |
|
49
|
8 |
|
return ($this->nextValueGetter)($previousValue); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* {@inheritDoc} |
|
54
|
|
|
*/ |
|
55
|
8 |
|
public function getValueByIndex(int $index) |
|
56
|
|
|
{ |
|
57
|
8 |
|
if(is_callable($this->indexValueGetter)) { |
|
58
|
5 |
|
return ($this->indexValueGetter)($index, $this->start); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
3 |
|
return reduce(xrange($index), function($carry) { |
|
62
|
3 |
|
return $this->getNextValue($carry); |
|
63
|
3 |
|
}, $this->start); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|