Skip to content

Instantly share code, notes, and snippets.

@jakefolio
Created May 27, 2016 16:01
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 jakefolio/0ccfd8688aebe8ee974b618e4503572a to your computer and use it in GitHub Desktop.
Save jakefolio/0ccfd8688aebe8ee974b618e4503572a to your computer and use it in GitHub Desktop.
Low memory usage collection
<?php
namespace jakefolio;
class Collection implements \ArrayAccess, \Countable, \IteratorAggregate
{
protected $items;
public function __construct($items = [])
{
if ($items instanceof \Traversable) {
$this->items = $items;
}
if (is_array($items)) {
$this->items = new \ArrayIterator($items);
}
}
public function push($item)
{
$this->items->append($item);
}
public function map(callable $callback)
{
return new static(new MapIterator($this->items, $callback));
}
public function reduce(callable $callback, $initialValue = null)
{
$result = $initialValue;
foreach ($this->items as $value) {
$result = $callback($result, $value);
}
return $result;
}
public function has($item)
{
while ($this->items->valid()) {
if ($this->items->current() === $item) {
return true;
}
$this->items->next();
}
return false;
}
public function filter(callable $callback)
{
return new static(new \CallbackFilterIterator($this->items, $callback));
}
public function each(callable $callback)
{
foreach ($this->items as $key => $value) {
$callback($value, $key);
}
}
public function getIterator()
{
yield from $this->items;
}
public function count()
{
return count($this->items);
}
public function offsetExists($key)
{
return isset($this->items[$key]);
}
public function offsetGet($key)
{
return $this->items[$key];
}
public function offsetSet($key, $value)
{
if (is_null($key)) {
$this->push($value);
} else {
$this->items[$key] = $value;
}
}
public function offsetUnset($key)
{
unset($this->items[$key]);
}
}
<?php
$collection = new jakefolio\Collection;
for ($i = 0; $i <= 10000; $i++) {
$collection->push("John Doe {$i}");
}
$newCollection = $collection->map(function ($row) {
return $row . ' YOLO';
})->map(function ($row) {
return 'WAT ' . $row;
})->filter(function ($row) {
return preg_match('/(WAT John Doe \d{3} YOLO)$/', $row);
})->each(function ($value) {
echo $value . PHP_EOL;
});
<?php
namespace jakefolio;
class MapIterator extends \IteratorIterator {
protected $map;
public function __construct(\Traversable $iterator, callable $callback)
{
parent::__construct($iterator);
$this->map = $callback;
}
public function current()
{
return $this->map->__invoke(parent::current(), $this->key());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment