horat1us / map-iterator
Map Iterator Implementation
1.0.1
2021-08-16 11:09 UTC
Requires
- php: >=7.4
Requires (Dev)
- phpstan/phpstan: ^0.12.94
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.6
This package is auto-updated.
Last update: 2024-12-16 18:48:56 UTC
README
Iterators to map inner iterator values before yielding.
Inspired by \FilterIterator and \CallbackFilterIterator.
Installation
Using composer
composer require horat1us/map-iterator:^1.0
Usage
MapIterator
Maps values before yielding using abstract method.
See ./example/map-iterator.php
<?php use Horat1us\Util\MapIterator; class IntegerPlusOneInterator extends MapIterator { public function map($item) { if (!is_int($item)) { throw new \InvalidArgumentException("Unable map not-integer item."); } return $item + 1; } } $numbers = [1,2,3]; $iterator = new IntegerPlusOneInterator(new \ArrayIterator($numbers)); print_r(iterator_to_array($iterator)); // Array ( [0] => 2, [1] => 3, [2] => 4 )
CallbackMapIterator (recommended)
Maps values before yielding using callback.
See ./example/map-iterator.php
<?php use Horat1us\Util\CallbackMapIterator; $numbers = [1,2,3]; $powCallback = static fn(int $number) => pow($number, $number); $iterator = new CallbackMapIterator(new \ArrayIterator($numbers), $powCallback); print_r(iterator_to_array($iterator)); // Array ( [0] => 1, [1] => 4, [2] => 27 )