Re: Proposal: clamp

From: Date: Wed, 23 Jun 2021 09:02:35 +0000
Subject: Re: Proposal: clamp
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-115056@lists.php.net to get a copy of this message
> Greetings internals, > > I present to you a proposal for a new basic math function: clamp. > > The main goal of this function is to contain a number inside a given bound. > And return the number if it is inside of that bound, and if not, and the > number is outside of the given bound, the nearest bound is returned. > > Now, does this need an RFC? The behaviour can be implemented in userland > in a number of ways, one of which is to compare the values in a if statement. > Another is to use the min and max math functions. > > max($min, min($max, $num)); > > I don’t have any schpeel as to why this should be in core, only that I thought it already > was. > Considering it is part of other languages standard math library, and it is a useful function. > > Can see this being useful in image manipulation, server-side rendering and math just to name > few. > > The proposed signature follows the convention of other math related functions. > > function clamp(int|float $num, int|float $min, int|float $max): int|float {} > > This function is very easy to implement, has no side effects or backward > compatibility issues, unless a userland implementation already has the function declared, > in which case PHP will throw a fatal error since the function cannot be redeclared. > > I've implemented this feature a few months ago already. > - Link: https://github.com/thinkverse/php-src/pull/1 > <https://github.com/thinkverse/php-src/pull/1> > > What are your opinions on this function? > > Regards, > Kim Hallberg. +1 from me as well. We recently added str_contains/starts_with/ends_with, which were welcome additions. I think clamp would be a nice addition too. I found three user-land clamp function declarations on a search on GitHub public repos. - [doubleleft/hook](https://github.com/doubleleft/hook/blob/master/src/bootstrap/helpers.php#L129) - 764 stars, Last activity in 2016. - [GetSimpleCMS/GetSimpleCMS](https://github.com/GetSimpleCMS/GetSimpleCMS/blob/master/admin/inc/basic.php#L2489) - 336 stars, Has recent activity. - [shish/shimmie2](https://github.com/shish/shimmie2/blob/master/core/polyfills.php#L477) - 267 stars, Has recent activity. I think it's safe to say that these libraries will be updated to accommodate the clamp function in PHP core; I'd even happily send pull requests to them. doubleleft/hook probably wouldn't be updated because it doesn't show recent activity, but that's an acceptable BC impact for a nice addition IMO. Thank you, --- Ayesh.

« previous php.internals (#115056) next »