jast99/sorted-linked-list
最新稳定版本:v1.0.0
Composer 安装命令:
composer require jast99/sorted-linked-list
包简介
SortedLinkedList
README 文档
README
A PHP library providing a sorted linked list that keeps values in order. It can hold int or string values, but not both at the same time.
Requires PHP 8.2+.
Installation
composer require jast99/sorted-linked-list
Usage
Creating a list
use JaSt99\SortedLinkedList\SortedLinkedList; $integers = SortedLinkedList::ofIntegers(); $strings = SortedLinkedList::ofStrings();
Inserting values
Values are automatically inserted in sorted order:
$list = SortedLinkedList::ofIntegers(); $list->insert(5); $list->insert(1); $list->insert(3); $list->toArray(); // [1, 3, 5]
Removing values
Returns true if the value was found and removed, false otherwise. If duplicates exist, only the first occurrence is removed.
$list->remove(3); // true $list->remove(99); // false
Checking for values
$list->contains(5); // true $list->contains(99); // false
Accessing first and last element
$list->first(); // smallest value $list->last(); // largest value
Both methods throw EmptyListException when the list is empty.
Count and emptiness
$list->count(); // number of elements $list->isEmpty(); // true if empty count($list); // works too (Countable interface)
Iteration
The list implements IteratorAggregate, so you can use foreach:
foreach ($list as $value) { echo $value . PHP_EOL; }
Converting to array and string
$list->toArray(); // [1, 3, 5] $list->toString(); // '1, 3, 5' $list->toString(';'); // '1;3;5' $list->toString(' | '); // '1 | 3 | 5'
Custom comparator
By default, values are sorted using PHP's native <=> operator. You can provide a custom comparator:
// Case-insensitive string sorting $list = SortedLinkedList::ofStrings(strcasecmp(...)); $list->insert('Banana'); $list->insert('apple'); $list->toArray(); // ['apple', 'Banana'] // Reverse integer sorting $list = SortedLinkedList::ofIntegers(fn(int $a, int $b): int => $b <=> $a); $list->insert(1); $list->insert(3); $list->toArray(); // [3, 1]
Type safety
The list enforces type consistency both at static analysis level (PHPStan generics) and at runtime:
$list = SortedLinkedList::ofIntegers(); $list->insert('foo'); // throws ListTypeMismatchException
Development
# Run tests vendor/bin/phpunit # Run static analysis vendor/bin/phpstan analyse # Check coding standard vendor/bin/phpcs
License
MIT
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 6
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-03-20