If statements and ranges - SnippetGood most recent 30 from http://snippetgood.com2010-07-29T23:47:17Zhttp://snippetgood.com/feeds/question/89http://www.creativecommons.org/licenses/by-nc/2.5/rdfhttp://snippetgood.com/questions/89/if-statements-and-rangesIf statements and ranges miss snippet2009-10-13T17:23:45Z2009-11-11T04:45:33Z
<p>I have a JQuery script that I'm working on and in part of it, I am comparing a value to make sure it is within a specific integer range.</p>
<p>This is what my first attempt looks like:</p>
<pre><code>if (levelCounter < 0) { levelCounter = 0; }
if (levelCounter > maxLevels) { levelCounter = maxLevels;}
</code></pre>
<p>I'm hoping there's a shorter more efficient way to do this - I can't think of it off the top of my head.</p>
http://snippetgood.com/questions/89/if-statements-and-ranges/103#103Answer by RCIX for If statements and ranges RCIX2009-10-16T10:09:11Z2009-10-16T10:09:11Z<p>Assuming jQuery syntax is similar to c#, so domething like this:</p>
<pre><code>static int clampToRange(int value, int min, int max)
{
if (value < min) { return min; }
if (value > max) { return max; }
return value;
}
</code></pre>
<p>Then all you need to do is this in your code:</p>
<pre><code>level = clampToRange(level, 0, maxLevel);
</code></pre>
http://snippetgood.com/questions/89/if-statements-and-ranges/147#147Answer by Kevin for If statements and ranges Kevin2009-11-11T04:45:33Z2009-11-11T04:45:33Z<p>I usually use something like this:</p>
<p>(Javascript) </p>
<pre><code>function clamp(value, min, max)
{
return Math.max( Math.min( value, max ), min );
}
</code></pre>