Created
June 13, 2012 23:33
-
-
Save vstarck/2927143 to your computer and use it in GitHub Desktop.
list.php
This file contains hidden or 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 MyList { | |
| private $list = array(); | |
| public function __construct() { | |
| $this->list = func_get_args(); | |
| } | |
| public function add($value) { | |
| $this->list[] = $value; | |
| } | |
| public function each($fn) { | |
| foreach($this->list as $current) { | |
| $fn($current); | |
| } | |
| return $this; | |
| } | |
| public function reduce($fn, $initialValue = null) { | |
| $this->each(function($current) use($fn, &$initialValue) { | |
| $initialValue = $fn($current); | |
| }); | |
| return $initialValue; | |
| } | |
| public function filter($fn) { | |
| $list = new MyList; | |
| $this->reduce(function($current) use($fn, $list) { | |
| if($fn($current) === true) { | |
| $list->add($current); | |
| } | |
| }); | |
| return $list; | |
| } | |
| public function toArray() { | |
| return $this->list; | |
| } | |
| public function debug() { | |
| echo '<pre>'; | |
| print_r($this->toArray()); | |
| echo '</pre>'; | |
| } | |
| } | |
| $numbers = new MyList(1, 2, 3, 4, 5, 6); | |
| // 1 OK | |
| $numbers->filter(function($value) { | |
| return $value% 2 === 0; | |
| })->debug(); | |
| // 2 ERROR | |
| function IS_EVEN($value) { | |
| return $value% 2 === 0; | |
| } | |
| $numbers->filter(IS_EVEN)->debug(); | |
| // 3 OK | |
| $IS_EVEN = function($value) { | |
| return $value % 2 === 0; | |
| }; | |
| $numbers->filter($IS_EVEN)->debug(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment