Live data from Hacker News

Math.min(Math.max(num, min), max)

twitter.com

41–50 of 291 posts

Re: Math.min(Math.max(num, min), max)

#42

Here's clamp in idiomatic Elixir (using multi-clause functions and guards): def clamp(min, _max, n) when n max, do: max def clamp(_min, _max, n), do: n

An Elixir convention I've seen is to put the thing you're operating on first, so that you can compose functions using the `|>` operator, which places the previous expression as the first argument of the function to the right. Maybe something like this? defmodule Compare do def clamp(number, minimum, maximum) do number |> max(minimum) |> min(maximum) end end import Compare clamp(5, 1, 10) # 5 clamp(1, 5, 10) # 5 clamp…

Yes you are right! Puting the number in the first parameter is even more idiomatic Elixir.

Re: Math.min(Math.max(num, min), max)

#45

In languages I use there’s usually no need to write that code. C++/17 has std::clamp() in header. Modern C# has Math.Clamp() since .NET Core 2.0; too bad it’s not available in desktop edition of the runtime. HLSL has clamp() intrinsic function, and a special version saturate() to clamp into [ 0 .. +1 ] interval.

It gets a bit confusing when the order of arguments is different depending on the library. For instance, with std it's std::clamp(val, min, max), but with Qt it's qBound(min, val, max) (for some reason I think the order of arguments in qBound is more logical).

Re: Math.min(Math.max(num, min), max)

#46
post #5

Earlier quoted context omitted.

Or to make sure it's crystal clear what's going on: function clamp(num, min, max) { if (num > max) return max; if (num

Speaking only to JS is there any reason to write it any other way outside of being clever or as a lambda for singular use? I definitely prefer this version. (Assuming any necessary runtime checks are included for a given project)

those extra newline characters slow down the page load :)

Re: Math.min(Math.max(num, min), max)

#47

Luckily, this is a solved problem for go. func helper(a float64, c chan float64){ time.Sleep(time.Duration(a) * time.Second) c

That will give you the median value. What OP wants is the value `a` clamped within `min` and `max`.

Can you give an example where median([a, min, max]) is not equal to clamp(a, min, max), given max >= min?

Re: Math.min(Math.max(num, min), max)

#48
Fun seeing that pretty much everyone else finds that idiom confusing too. Half-serious, over breakfast:

    (case [(> n min) (
(Side note: Clojure's `>` and ` n min)` into "if n is greater than min" takes some work for me, still, after more than a year.)
Post reply on HN