thesebas / itertools
itertools 用于处理生成器和迭代器
1.0.3
2017-11-06 08:08 UTC
Requires (Dev)
- kahlan/kahlan: ^4.0
- satooshi/php-coveralls: ^1.0
This package is auto-updated.
Last update: 2024-09-25 12:04:36 UTC
README
安装
composer require thesebas/itertools
使用方法
假设我们有一个生成器,它产生字母。
expect(iterator_to_array(gen(3)))->toBe(['a', 'b', 'c']);
tail
跳过迭代器中的所有但 n 个项目。
$actual = tail(gen(5), 3, false); expect(iterator_to_array($actual))->toBe(['c', 'd', 'e']);
head
迭代前 n 个项目。
$actual = head(gen(10), 3); expect(iterator_to_array($actual))->toBe(['a', 'b', 'c']);
skip
跳过 n 个项目,并迭代剩余部分。
$actual = skip(gen(10), 4); expect(iterator_to_array($actual))->toBe(['e', 'f', 'g', 'h', 'i', 'j']);
tee
将迭代器分割成两个独立的迭代器(带有内部缓冲)。
list($left, $right) = tee(gen(10)); expect(iterator_to_array(head($left, 3)))->toBe(['a', 'b', 'c']); expect(iterator_to_array(head($right, 5)))->toBe(['a', 'b', 'c', 'd', 'e']); expect(iterator_to_array(head($left, 5)))->toBe(['d', 'e', 'f', 'g', 'h']); expect(iterator_to_array(head($right, 2)))->toBe(['f', 'g']); expect(iterator_to_array(head($left, 2)))->toBe(['i', 'j']); expect(iterator_to_array(head($right, 3)))->toBe(['h', 'i', 'j']);
chain
迭代第一个,然后是第二个,第三个...
$actual = chain(gen(5), gen(3)); expect(iterator_to_array($actual))->toBe(['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c']);
filter
迭代所有项目,但只产出过滤后的项目。
$actual = filter(gen(10), function ($item, $key) { return $key % 2 == 1; }); expect(iterator_to_array($actual))->toBe(['b', 'd', 'f', 'h', 'j']);
map
返回一个包含映射值的新的迭代器。
$actual = map(gen(3), function ($item, $key) { return "item {$key}: {$item}"; }); expect(iterator_to_array($actual))->toBe(['item 0: a', 'item 1: b', 'item 2: c']);
chunk
返回一个块迭代器迭代器。
$actual = \iterator_to_array(map(chunk(gen(10), 3), '\\iterator_to_array')); expect($actual)->toBe([ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j'] ]);