AS3 / JS Constrain a value in one line

Here is a little snippet to constrain a value in a single line. It works by using two nested inline conditionals. The ‘else’ part of the first conditional is another conditional. It may not be the best approach but it works and is much easier and faster to write than two if-else statements.

In English it looks like this:
value = is value greater than max ? set to max, otherwise is value less than min ? set to min, otherwise leave it as is;

1
2
3
4
5
// for js - remove the type declarations (:Number)
var minValue:Number = 0;
var maxValue:Number = 100;

value = value > maxValue ? maxValue : (value < minValue ? minValue : value);
Posted toActionScript Javascript