Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda