Live data from Hacker News

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

twitter.com

51–60 of 291 posts

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

#52
post #22
post #20

Earlier quoted context omitted.

Very good point. I thought of it more as pseudocode.

imho a very elegant solution and probably works in most languages, I was surprised by JavaScript's behaviour myself

For a real fun headscratcher consider [ '9', '10', '11', '12', '13' ].map(parseInt)

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

#55
post #52
post #22

Earlier quoted context omitted.

imho a very elegant solution and probably works in most languages, I was surprised by JavaScript's behaviour myself

For a real fun headscratcher consider [ '9', '10', '11', '12', '13' ].map(parseInt)

Thank you for this exercise! I figured it out!

[ROT 13] spoiler: cnefrVag frpbaq nethzrag vf onfr, znc frpbaq nethzrag vf vaqrk va neenl. 10 vf gur frpbaq nethzrag, vaqrk 1. cnefrVag(10, 1) unf vyyrtny onfr

[0] https://rot13.com/

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

#56

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.)

However, prefix notation becomes much easier to read and reason about when you have more than two things to compare:

    (> 3 2 1 ...)
vs

    (3 > 2) && (2 > 1) && ...

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

#57
post #28

I find that the fact that the functions min and max have the same name as the variables min and max increases cognitive load which makes it harder to think about it. I find the following easier to read : Math.min(Math.max(num, lower_bound), upper_bound)

I prefer "ceiling" and "floor", but yes, agreed.

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

#59

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.)

Alternatively, since min and max are part of clojure.core:

   (-> n
       (max vmin)
       (min vmax))

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

#60
Python also doesn't have a built-in clamp function (I think there might be one in numpy), I usually use

    sorted((floor, x, ceiling))[1]
Throw it in a function with some asserts if you're worried about x not being a number and giving you weird results.
Post reply on HN