1

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.

This is what my first attempt looks like:

if (levelCounter < 0) { levelCounter = 0; }
if (levelCounter > maxLevels) { levelCounter = maxLevels;}

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.

flag

2 Answers

2

Assuming jQuery syntax is similar to c#, so domething like this:

static int clampToRange(int value, int min, int max)
{
    if (value < min) { return min; }
    if (value > max) { return max; }
    return value;
}

Then all you need to do is this in your code:

level = clampToRange(level, 0, maxLevel);
link|flag
1

I usually use something like this:

(Javascript)

function clamp(value, min, max)
{
    return Math.max( Math.min( value, max ), min );
}
link|flag

Your Answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.