Last active
February 26, 2021 13:23
-
-
Save drealecs/ad720b51219675a8f278b8534e99d7c7 to your computer and use it in GitHub Desktop.
Cached Iterator wrapper over iterators that does not support rewinding, like a Generator that emits value objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CachedNotRewindableIteratorAggregate implements IteratorAggregate { | |
private Iterator $iterator; | |
private array $cache = []; | |
public function __construct(Iterator $iterator) { | |
$this->iterator = $iterator; | |
} | |
public function getIterator(): Iterator { | |
$index = 0; | |
while (isset($this->cache[$index]) || $this->iterator->valid()) { | |
if (isset($this->cache[$index])) { | |
[$key, $value] = $this->cache[$index]; | |
} else { | |
$key = $this->iterator->key(); | |
$value = $this->iterator->current(); | |
$this->cache[$index] = [$key, $value]; | |
$this->iterator->next(); | |
} | |
$index++; | |
yield $key => $value; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class EagerCachedNotRewindableIteratorAggregate implements IteratorAggregate { | |
private array $cache = []; | |
public function __construct(iterable $iterable) { | |
foreach ($iterable as $key => $value) { | |
$this->cache[$index] = [$key, $value]; | |
} | |
} | |
public function getIterator(): Iterator { | |
$index = 0; | |
while (isset($this->cache[$index])) { | |
[$key, $value] = $this->cache[$index++]; | |
yield $key => $value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment