PDA

View Full Version : Math.min and Math.max



lunatic
January 16th, 2004, 11:36 AM
So here is a piece of code that I have seen used a lot but don't really quite understand: :h:

myVar = Math.min(Math.max(myVar, this.min), this.max);

or some variation thereof. I understand that the function first finds the maximum value of two values then turns around and uses that to find the minimum between two values.

Can someone please expand on why this is done? And how do you know when to use it?

I have seen it used most often when scaling, for example.

Thanks all you genius Kirupians! :bu:

pom
January 16th, 2004, 06:21 PM
It's pretty hard to explain out of its context. But if myVar is the scale, that kind of expression will keep myVar between this.min and this.max.

a = Math.max(myVar, this.min) will take the maximum of myVar and this.min, which means at least this.min.

Then Math.min(a, this.max) will take the minimum of a and this.max, which means at most this.max.

CQFD :)

lunatic
January 16th, 2004, 06:23 PM
Thanks Ilyas! Just saying "keep myVar b/t min and max" clears up a lot!

CQFD :h:

senocular
January 16th, 2004, 06:38 PM
I was almost contemplating making a new method to handle that since I thought it might have been more easily understood ;) I even decided against it in the slider code if you look at that. I used a ... err what what it? Some function like constrict or contain or something to prevent the _y value from going too far. Same thing. using min/mx you can do it all in one line.

(F5 had a built in ASClamp that did this, but I think that went away in MX)