Hacker News new | ask | show | jobs
by shdon 12 days ago
I guess the clamp function really is needed, as even in their release notes, they did the clamping using min/max incorrectly.

Their PHP8.5 examples are written as:

  var_dump(max($value, min($lower_bound, $upper_bound)));
but that should be:

  var_dump(max($lower_bound, min($value, $upper_bound)));
/facepalm
3 comments

I would actually write it like:

    $value = max($value, $lower_bound);
    $value = min($value, $upper_bound);
    var_dump($value);
10 years from now I can thoughtlessly scan over that without having to think what is going on.

This is great:

    clamp($value, $lower_bound, $upper_bound);
It's even more readable.

And since I cant stop typing... (sorry lol)

    $trucks  = trucks($ordernum);
    $boxes   = $boxes_per_truck * $trucks;
    $bananas = $bananas_per_box*$boxes;
    $bananas = max($bananas, $lower_bound);
    $bananas = min($bananas, $upper_bound);
    var_dump($bananas);
In stead of:

    var_dump( max($lower_bound,min($boxes*$bananas_per_box*trucks($ordernum)*$boxes_per_truck,$upper_bound)));
Yes. Write code like how you would do math on paper. Code should be readable without syntax highlighting. Turn it off and it's easy to tell where readability is poor.
> Their PHP8.5 examples are written as:

That is false. The bounds are [0, 100] in both examples and 0 is correctly put as the first parameter to max() in 8.5.

    max($value, min($lower_bound, $upper_bound)) when $value < $lower_bound: $lower_bound
    max($value, min($lower_bound, $upper_bound)) when $value > $upper_bound: $value
    max($value, min($lower_bound, $upper_bound)) when $value is between them: $value

    max($lower_bound, min($value, $upper_bound)) when $value < $lower_bound: $lower_bound
    max($lower_bound, min($value, $upper_bound)) when $value > $upper_bound: $upper_bound
    max($lower_bound, min($value, $upper_bound)) when $value is between them: $value
If the former was what's actually written then yeah, it would be incorrect. However, if you swapped arguments 1 and 2 for each clamp() call, they'd give the same result, and for what you say the PHP 8.5 example is written as, there's no call given where $value > $upper_bound.

I don't know if this makes much sense, though that's all the more reason for needing clamp().