Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
How to cap a value between 2 integers?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Implement the special case of ranges starting from zero:

const mod = (n, m) => (m + n % m) % m;

Then the overall operation in terms of that:

const cap = (value, low, high) => low + mod(value - low, high - low + 1);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!