I am trying to write a function that given a number, it returns the number within the range of 1 to 12.
So, for example, if the input is 1, the output is 1, if the input is 12, the output is 12, if the input is 13, the output is 1, if the input is 14, the output is 2, if the input is 24, the output is 12.
I've tried this so far:
function toRange(number) {
if (number > 12) {
return number % 12
}
return number
}
But I am wondering if there is a way that I can solve this without doing conditionals. I thought of doing return (number + 12) % 12, but that wouldn't work if number is 12, because it would return 0.
You could use an adjustment for a zero based value and add the adustment at the end.
function toRange(number) {
return (number - 1) % 12 + 1;
}
var i;
for (i = 1; i <= 24; i++) console.log(i, toRange(i));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments