Let’s say I am trying to state a range between two integers, i.e. 0 and 3. Anything that is lower than this range will loop back from the upper end, and vice versa. It is kind of like how integers work in other languages.
For example (range 0 to 3):
cap(-4) // returns 0
cap(-3) // returns 1
cap(-2) // returns 2
cap(-1) // returns 3
cap(0) // returns 0
cap(1) // returns 1
cap(2) // returns 2
cap(3) // returns 3
cap(4) // returns 0
cap(5) // returns 1
cap(6) // returns 2
cap(7) // returns 3
cap(8) // returns 0
The best working code that I could make is this:
const cap = (value, low, high) => value < low ? high - (high - value) % (high - low + 1) : (value - low) % (high - low + 1) + low
Is there a more elegant way to do this? I feel like there’s a way to do this without using conditional.