Last active
December 22, 2015 00:09
-
-
Save dakatsuka/6387205 to your computer and use it in GitHub Desktop.
PHP版無限リスト
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 Stream implements \Iterator | |
{ | |
/** | |
* @var int | |
*/ | |
private $position; | |
/** | |
* @var int | |
*/ | |
private $offset; | |
/** | |
* @var int | |
*/ | |
private $limit; | |
/** | |
* @param int $offset | |
* @param int $limit | |
*/ | |
public function __construct($offset, $limit = null) | |
{ | |
$this->position = $offset; | |
$this->offset = $offset; | |
$this->limit = $limit; | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function current() | |
{ | |
return $this->position; | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function next() | |
{ | |
$this->position++; | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function valid() | |
{ | |
if ($this->limit && $this->position > $this->limit) { | |
return false; | |
} | |
return true; | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function key() | |
{ | |
return $this->position; | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function rewind() | |
{ | |
$this->position = $this->offset; | |
} | |
public function take($n) | |
{ | |
return new \LimitIterator($this, 0, $n); | |
} | |
} |
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 | |
/** | |
* 無限ループ | |
*/ | |
$stream1 = new Stream(0); | |
foreach ($stream1 as $i) { | |
echo $i . "\n"; | |
} | |
/** | |
* 範囲指定 | |
*/ | |
$stream2 = new Stream(50, 200); | |
foreach ($stream2 as $i) { | |
echo $i . "\n"; | |
} | |
/** | |
* 10件のみ取得 | |
*/ | |
$stream3 = new Stream(0); | |
foreach ($stream3->take(10) as $i) { | |
echo $i . "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment