Math.min(Math.max(num, min), max)
41–50 of 291 posts
Re: Math.min(Math.max(num, min), max)
#42Here'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…
Re: Math.min(Math.max(num, min), max)
#43if num > max: num = max
if num < min: num = min
Re: Math.min(Math.max(num, min), max)
#44Re: Math.min(Math.max(num, min), max)
#45In 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.
Re: Math.min(Math.max(num, min), max)
#46Earlier 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)
Re: Math.min(Math.max(num, min), max)
#47Luckily, 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`.
Re: Math.min(Math.max(num, min), max)
#48 (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.)Re: Math.min(Math.max(num, min), max)
#49[min, num, max].sort()[1]
Re: Math.min(Math.max(num, min), max)
#50[min, num, max].sort()[1]