jstewmc / interval
两个端点之间的数字集合
v1.0.0
2016-08-13 22:46 UTC
Requires
- php: ^7.0
Requires (Dev)
- jstewmc/test-case: ^1.0
This package is auto-updated.
Last update: 2024-08-29 04:25:26 UTC
README
两个端点之间的数字集合。
use Jstewmc\Interval; // create an interval between 2 (exclusive) and 4 (inclusive) $interval = new Interval('(2, 4]'); // compare values $interval->compare(1); // returns -1 $interval->compare(2); // returns -1 $interval->compare(3); // returns 0 $interval->compare(4); // returns 0 $interval->compare(5); // returns 1 // echo the interval echo $interval; // returns "(2, 4]"
语法
此库支持标准美国区间语法,要求(按顺序)
- 一个开括号(
[)或开括号((); - 一个数字,正无穷(
INF)或负无穷(-INF); - 一个逗号空格(
,); - 一个数字,正无穷(
INF)或负无穷(-INF);并且, - 一个闭括号(
])或闭括号())。
接受正负浮点数、整数和无穷大。
例如
(2, 4]表示 2 < x <= 4(-10.5, 10.5)表示 -10.5 < x < 10.5[0, INF)表示 0 <= x < ∞(-INF, INF)表示 -∞ < x < ∞
请注意,此库不支持 反向括号 语法(例如,]2, 4])或 分号分隔 语法(例如,[2; 4])。
使用方法
您可以从字符串创建一个区间实例或手动使用集合方法创建它
use Jstewmc\Interval; $a = new Interval('(2, 4]'); $b = (new Interval()) ->setLowerExclusive() ->setLower(2) ->setUpper(4) ->setUpperInclusive(); $a == $b; // returns true
请注意,当从字符串创建区间实例时,如果区间的语法无效,将抛出 InvalidArgumentException
use Jstewmc\Interval; new Interval('[0; 0]'); // throws exception (semicolon syntax not supported) new Interval(']0, 2]'); // throws exception (reverse brackets not supported) new Interval('[foo, bar]'); // throws exception (use numbers or INF) new Interval('[0, 0)'); // throws exception (same endpoint, different boundary) new Interval('[1, -1]'); // throws exception (upper- is less than lower-bound)
支持无穷大作为字符串 'INF' 或 INF 预定义常量
use Jstewmc\Interval; $a = new Interval('(-INF, 0]'); $b = (new Interval()) ->setLowerExclusive() ->setLower(-INF) ->setUpper(0) ->setUpperInclusive(true); $a == $b; // returns true
您可以使用 compare() 方法将值与区间进行比较。如果值在区间下方、内部或上方,则 compare() 方法将返回 -1、0 或 1
use Jstewmc\Interval; $interval = new Interval('(2, 4]'); $interval->compare(1); // returns -1 $interval->compare(2); // returns -1 $interval->compare(3); // returns 0 $interval->compare(4); // returns 0 $interval->compare(5); // returns 1
您可以使用获取方法获取区间的任何设置
use Jstewmc\Interval; $interval = new Interval('(2, 4]'); $interval->getIsLowerInclusive(); // returns false $interval->getLower(); // returns 2 $interval->getUpper(); // returns 4 $interval->getIsUpperInclusive(); // returns true
有一些方便的方法可以轻松获取和设置边界
use Jstewmc\Interval; $interval = new Interval('(2, 4]'); $interval->isLowerInclusive(); // returns false $interval->isLowerExclusive(); // returns true $interval->isUpperInclusive(); // returns true $interval->isUpperExclusive(); // returns false echo $interval->setLowerInclusive(); // prints "[2, 4]" echo $interval->setLowerExclusive(); // prints "(2, 4]" echo $interval->setUpperInclusive(); // prints "(2, 4]" echo $interval->setUpperExclusive(); // prints "(2, 4)"
就这些了!
许可证
作者
版本
1.0.0,2016年8月13日
- 主要版本
- 更新
composer.json
0.2.0,2016年8月7日
- 添加对无穷大的支持(例如,
'(-INF, 0]')。 - 更新错误信息,使其更具信息性。
- 更新 README 示例。
0.1.0,2016年8月6日
- 首次发布