xphere / lazzzy
此包已被弃用,不再维护。未建议替代包。
PHP的懒集合
0.2
2015-08-13 16:43 UTC
Requires
- php: >=5.4
Requires (Dev)
- php: >=5.5
- phpunit/phpunit: ~4.0, >=4.5
This package is not auto-updated.
Last update: 2024-02-26 23:55:27 UTC
README
PHP的懒集合库。
用一层纯粹的懒性包裹你的可迭代对象,这样你就可以在懒散的时候进行懒加载。:D
我为什么要用这个呢?
集合无处不在,但你通常不希望在每次操作中都将它们具体化。这就是懒性的用武之地。这允许你在零初始化时间进行映射和过滤,并在适当的时机进行后续评估。
特性
- 将任何东西转换为可迭代对象:数组、迭代器、函数、生成器……你名之。[*]
- 在初始化时使用多个函数进行映射和过滤,评估时只执行一次
- 处理无限迭代器
[*] 计划中
兼容性
Lazzzy需要PHP 5.4或更高版本进行基本使用。
安装
只需使用composer将其添加到项目中
composer require xphere/lazzzy@dev
用法
注意:Lazzzy仍处于alpha阶段,所以不要依赖当前方法。只是提醒一下
函数
Container::from(x) # 懒加载
静态函数。几乎可以将任何东西转换为可迭代对象。返回一个包装可迭代对象的Container对象。
use Lazzzy\Container; $container = Container::from(range(0, 1000));
Container::getIterator()
遵守\IteratorAggregate接口,因此您可以遍历Container。
Container::toAssoc() # 不懒加载
遍历容器,应用所有转换。返回结果数组。
use Lazzzy\Container; $expected = ['a' => 0, 'b' => 1, 'c' => 2]; $container = Container::from($expected); $values = $container->toAssoc(); $this->assertEquals($expected, $values);
Container::toArray() # 不懒加载
与toAssoc方法类似,但丢弃键。
use Lazzzy\Container; $expected = [0, 1, 2]; $values = ['a' => 0, 'b' => 1, 'c' => 2]; $container = Container::from($expected); $values = $container->toAssoc(); $this->assertEquals($expected, $values);
Container::each(fn) # 不懒加载
遍历容器,对每个迭代执行fn。返回空值。
use Lazzzy\Container; $echo = function ($item) { echo $item, ', '; }; $container = Container::from(range(0, 5)); $container->each($echo); /// Outputs "0, 1, 2, 3, " and returns nothing
Container::map(fn) # 懒加载 (a -> b) -> [a] -> [b]
对[a]的每个迭代调用fn转换。
use Lazzzy\Container; $expected = [0, 2, 4, 6]; $double = function ($item) { return $item * 2; }; $container = Container::from(range(0, 3)) ->map($double) ; $actual = $container->toArray(); $this->assertSame($expected, $actual);
Container::filter(fn) # 懒加载 (a -> Bool) -> [a] -> [a]
过滤返回为真值的元素。
use Lazzzy\Container; $expected = [1, 3]; $odd = function ($item) { return $item % 2 === 1; }; $container = Container::from(range(0, 3)) ->filter($odd) ; $actual = $container->toArray(); $this->assertSame($expected, $actual);
Container::take(number) # 懒加载 n -> [a] -> [a]
从迭代器中取出n个项。n必须是一个大于零的整数。
use Lazzzy\Container; $expected = [0, 1]; $container = Container::from(range(0, 3)) ->take(2) ; $actual = $container->toArray(); $this->assertSame($expected, $actual);
Container::takeWhile(fn) # 懒加载 n -> [a] -> [a]
在fn条件为真值时取出项。
use Lazzzy\Container; $expected = [0, 1]; $notEqualsTwo = function ($item) { return $item !== 2; }; $container = Container::from(range(0, 3)) ->takeWhile($notEqualsTwo) ; $actual = $container->toArray(); $this->assertSame($expected, $actual);
更多功能即将推出
- Container::skip(n)
- Container::skipUntil(fn)
- Container::fold(fn, x?)
- Container::foldr(fn, x?)
- Container::find(fn)
- Container::every(fn)
- Container::any(fn)
- Container::size()
贡献
请通过GitHub为项目做出贡献
作者
Berny Cantos 联系方式: be@rny.cc GitHub:xPheRe Twitter:xPheRe
许可证
Lazzzy受MIT许可证许可。有关完整详情,请参阅LICENSE文件。