renfordt/clamp

Adds the support of the method clamp() for PHP.

v1.0.0 2024-04-14 19:39 UTC

This package is auto-updated.

Last update: 2024-12-14 21:22:18 UTC


README

Adds the support of the mathematical method clamp() for PHP.

Badge Packagist Version Packagist PHP Version GitHub License GitHub Actions Workflow Status Code Climate coverage Code Climate maintainability

Installation

The recommended way of installing Larvatar is to use Composer. Run the following command to install it to you project:

composer require renfordt/clamp

Usage

The usage is very simple and comparable to the C++ function:

clamp(
    $value, // The value to be clamped
    $min, // The minimum value to clamp to
    $max // The maximum value to clamp to
);

Alternatively you can use clampMinMax() which is a bit slower.

clampMinMax(
    $value, // The value to be clamped
    $min, // The minimum value to clamp to
    $max // The maximum value to clamp to
);

Why another package?

Even though there are some similar packages, this one focuses on different approaches.

First of all the syntax is similar to c++ clamp function.

Secondly and more important this package focuses on performance. Other packages uses the max($min, min($max, $num)) approach but this packages works with the following code:

if ($value > $max) {
    return $max;
} elseif ($value < $min) {
    return $min;
}
return $value;

Even though the readability is a bit worse, the performance is up to 2x faster. In most cases this is not noticeable but in some cases there will be a benefit.

Over a iteration of 100.000 executions the functions need the following times:

String

  • clamp: 0.0035040378570557 sec
  • clampMinMax: 0.0061681270599365 sec

Integer

  • clamp: 0.0029380321502686 sec
  • clampMinMax: 0.0056021213531494 sec

Float

  • clamp: 0.0028560161590576 sec
  • clampMinMax: 0.0062460899353027 sec