If statements and ranges - SnippetGood most recent 30 from http://snippetgood.com 2010-07-29T23:47:17Z http://snippetgood.com/feeds/question/89 http://www.creativecommons.org/licenses/by-nc/2.5/rdf http://snippetgood.com/questions/89/if-statements-and-ranges If statements and ranges miss snippet 2009-10-13T17:23:45Z 2009-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 &lt; 0) { levelCounter = 0; } if (levelCounter &gt; 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#103 Answer by RCIX for If statements and ranges RCIX 2009-10-16T10:09:11Z 2009-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 &lt; min) { return min; } if (value &gt; 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#147 Answer by Kevin for If statements and ranges Kevin 2009-11-11T04:45:33Z 2009-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>