<?php
class MapIterator implements Iterator {
private $f;
private $inner;
public function __construct($f, $inner) {
$this->f = $f;
$this->inner = $inner;
}
function rewind() {
return $this->inner->rewind();
}
function current() {
return call_user_func($this->f, $this->inner->current());
}
function key() {
return $this->inner->key();
}
function next() {
return $this->inner->next();
}
function valid() {
return $this->inner->valid();
}
}
function iter_map($f, $iter) {
return new MapIterator($f, $iter);
}
// example:
function times_two($x) {
return $x * 2;
}
$source = new ArrayIterator([0, 1, 2, 3, 4, 5, 6]);
//var_dump(iterator_to_array(iter_map('times_two', $source)));
print_r(iterator_to_array(gen_map('times_two', $source)));
preferences:
45.32 ms | 402 KiB | 5 Q