Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda