patbator/collection

PHP 对 Smalltalk 集合协议的致敬

2.0.0 2023-01-27 22:49 UTC

This package is auto-updated.

Last update: 2024-09-28 03:00:00 UTC


README

pipeline status coverage report

使用 PHP ArrayObject 对 Smalltalk 集合协议的致敬。

安装

使用 Composer

$ composer require patbator/collection

手动安装

克隆或下载仓库。

需要提供的 PSR-4 自动加载器来使用 Collection 对象

require_once '[path where you cloned or downloaded this library]/autoload.php';

用法

让我们来点魔法 ;)

use Patbator\Collection\Collection;

(new Collection)->addWithOccurences('pharo', 15); // -> collection of 15 times repeated 'pharo'

$languages = new Collection(['lisp', 'pharo', 'php']); // -> collection containing 'lisp', 'pharo' and 'php'
$languages->add('ruby'); // -> collection containing 'lisp', 'pharo', 'php' and 'ruby'
$languages->addAll(new Collection(['python', 'typescript'])); // collection containing 'lisp', 'pharo', 'php', 'ruby', 'python' and 'typescript'
$languages->addIfNotPresent('php'); // -> will not repeat 'php' in collection

$languages->includes('ruby'); // -> true
$languages->allSatisfy(fn ($item) => is_string($item)); // -> true, they are all strings
$languages->anySatisfy(fn ($item) => is_int($item)); // -> false, there is no int
$languages->noneSatisfy(fn ($item) => 'x' == substr($item, 0, 1)); // -> true, none starts with 'x'

$languages->collect(fn ($item) => substr($item, 0, 1)); // -> new collection containing 'l', 'p', 'p', 'r', 'p' and 't'

$languages->detect(fn ($item) => 't' == substr($item, 0, 1)); // -> 'typescript'
$languages->detect(fn ($item) => 'x' == substr($item, 0, 1)); // -> null

$languages->detectMax(fn ($item) => strlen($item)); // -> 'typescript', longest word
$languages->detectMin(fn ($item) => strlen($item)); // -> 'php', shortest word
$languages->detectSum(fn ($item) => strlen($item)); // -> 32, cumulated length of each string

$languages->eachDo(function($item) {
  echo $item . ', ';
}); // -> echo : lisp, pharo, php, ruby, python, typescript,

$languages->injectInto('', function($value, $item) { return $value .= ' : '; }); // -> 'lisp : pharo : php : ruby : python : typescript : '

$selection = $languages->reject(fn ($item) => 'python' == $item); // -> new collection without 'python'

$selection = $languages->select(fn ($item) => 'p' == substr($item, 0, 1)); // -> new collection containing 'pharo' and 'php'

测试

composer run-script test

许可证

版权(c)2019 Patrick Barroca patrick.barroca@gmail.com

本程序是自由软件:您可以按照自由软件基金会发布的 GNU Affero 通用公共许可证的条款重新分发和/或修改它,许可证版本为3。

本程序是在希望它将是有用的前提下分发的,但没有任何保证;甚至没有关于其适销性或适用于特定目的的隐含保证。有关详细信息,请参阅 GNU Affero 通用公共许可证。

您应该已经收到本程序的 GNU Affero 通用公共许可证副本。如果没有,请参阅https://gnu.ac.cn/licenses/gpl-3.0.html