Function that given a number returns the number within a range

Viewed 193

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.

3 Answers

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; }

maybe something like this:

function toRange(number) {
  if (number > 12) { 
    if (number % 12 === 0)
      return number - 12;
    return number % 12
  }
  return number
}

Can also be thought of like - Get the remainder of number by 12 and return 12 in case remainder is 0.

function toRange(number) {
    return number % 12 || 12;
}

for (var i = 1; i <= 24; i++) console.log(i, toRange(i));

Related