Skip to content

Instantly share code, notes, and snippets.

@drealecs
Last active February 26, 2021 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drealecs/ad720b51219675a8f278b8534e99d7c7 to your computer and use it in GitHub Desktop.
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.
<?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;
}
}
}
<?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