Skip to content

Instantly share code, notes, and snippets.

@GoodBoyNinja
Last active November 17, 2023 22:27
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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)
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