Last active
November 17, 2023 22:27
-
-
Save GoodBoyNinja/17a8d33d26957fe1701858c51921694b to your computer and use it in GitHub Desktop.
Clamp a number to be in a range. You can also use this to clamp an array of numbers (like an rgb array for example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ClampNum(num, min, max, inErrReturn) { | |
function SingleChannelClamp(num, min, max) { | |
if ( | |
isNaN(num) || | |
min == undefined || | |
isNaN(min) || | |
isNaN(max) || | |
max == undefined | |
) { | |
return num; | |
} | |
if (num <= min) { | |
return min; | |
} else if (num >= max) { | |
return max; | |
} else { | |
return num; | |
} | |
return num; | |
} | |
if (min == undefined || max == undefined) { | |
return num; | |
} else if (num == undefined) { | |
if (inErrReturn !== undefined) { | |
return inErrReturn; | |
} | |
return 0; | |
} | |
if (num.length >= 1) { | |
var finalArr = []; | |
for (var nm = 0; nm < num.length; nm++) { | |
finalArr.push(SingleChannelClamp(num[nm], min, max)); | |
} | |
return finalArr; | |
} else { | |
return SingleChannelClamp(num, min, max); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment