Skip to content

Commit

Permalink
feat: add is_zero()
Browse files Browse the repository at this point in the history
  • Loading branch information
Yogarine committed Jan 31, 2025
1 parent 422ecd1 commit 59d769b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@
* This mask matches every possible past and future PHP error level.
*/
const E_EVERYTHING = 0x7FFFFFFF;

/**
* Default error tolerance.
*/
const PHP_ZERO_TOLERANCE = 0.00000000001;
13 changes: 13 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,19 @@ function is_closed_resource(mixed $value): bool
return Type::ClosedResource->is($value);
}

/**
* Finds whether the given number is (sufficiently close to) 0.
*
* @param int|float $value The number being evaluated.
* @param float|null $tolerance Tolerance allowed when evaluating the number.
* @return bool Returns <u>true</u> if **value** is (sufficiently close to) 0,
* <u>false</u> otherwise.
*/
function is_zero(int | float $value, ?float $tolerance = PHP_ZERO_TOLERANCE): bool
{
return 0 === $value || 0.0 === $value || (null !== $tolerance && \abs($value) <= $tolerance);
}

/**
* Sequences a value into a {@see \Generator}.
*
Expand Down
25 changes: 24 additions & 1 deletion tests/Unit/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
]);
});


describe('is_closed_resource()', function () {
it('correctly returns whether value is a closed resource', function ($value, $type) {
$isClosed = rephine\is_closed_resource($value);
Expand All @@ -64,6 +63,30 @@
})->with('types / test cases');
});

describe('is_zero()', function () {
test('returns true if value is (close to) 0', function ($value, $tolerance) {
$isZero = rephine\is_zero($value, $tolerance);

expect($isZero)->toBeTrue();
})->with([
[0, null],
[0.0, null],
[PHP_FLOAT_MIN, rephine\PHP_ZERO_TOLERANCE],
[PHP_FLOAT_MIN, PHP_FLOAT_MIN],
]);

test('returns false if value is not (close to) 0', function ($value, $tolerance) {
$isZero = rephine\is_zero($value, $tolerance);

expect($isZero)->toBeFalse();
})->with([
[1, rephine\PHP_ZERO_TOLERANCE],
[1.0, rephine\PHP_ZERO_TOLERANCE],
[PHP_FLOAT_EPSILON, PHP_FLOAT_MIN],
[PHP_FLOAT_MIN, null],
]);
});

describe('seq()', function () {
test('properly sequences values', function ($data, $expected) {
$array = [];
Expand Down

0 comments on commit 59d769b

Please sign in to comment.