-
Notifications
You must be signed in to change notification settings - Fork 239
Expand file tree
/
Copy pathJustifyMultipleIterator.php
More file actions
95 lines (86 loc) · 1.87 KB
/
JustifyMultipleIterator.php
File metadata and controls
95 lines (86 loc) · 1.87 KB
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
95
<?php
namespace MathPHP\Util;
/**
* @implements \Iterator<array<mixed>>
*
* Based on IterTools PHP's IteratorFactory.
* @see https://github.com/markrogoyski/itertools-php
* @see https://github.com/markrogoyski/itertools-php/blob/main/src/Util/JustifyMultipleIterator.php
*/
class JustifyMultipleIterator implements \Iterator
{
/**
* @var array<\Iterator<mixed>>
*/
protected $iterators = [];
/**
* @var int
*/
protected $index = 0;
/**
* @param iterable<mixed> ...$iterables
*/
public function __construct(iterable ...$iterables)
{
foreach ($iterables as $iterable) {
$this->iterators[] = Iter::makeIterator($iterable);
}
}
/**
* {@inheritDoc}
*
* @return array<mixed>
*/
public function current(): array
{
return array_map(
static function (\Iterator $iterator) {
return $iterator->valid() ? $iterator->current() : NoValueMonad::getInstance();
},
$this->iterators
);
}
/**
* {@inheritDoc}
*/
public function next(): void
{
foreach ($this->iterators as $iterator) {
if ($iterator->valid()) {
$iterator->next();
}
}
$this->index++;
}
/**
* {@inheritDoc}
*
* @return int
*/
public function key(): int
{
return $this->index;
}
/**
* {@inheritDoc}
*/
public function valid(): bool
{
foreach ($this->iterators as $iterator) {
if ($iterator->valid()) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
public function rewind(): void
{
foreach ($this->iterators as $iterator) {
$iterator->rewind();
}
$this->index = 0;
}
}