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

164
Visualizações
mathematical value transformation / switch behavior in js

I use common functions like map() and clamp() to transform values. I wonder if there is a similar mathematical function which lets me translate a rising value to an on and off state (0 and 1). Could a square wave help?

For more context: I want the value to be 1 whilst something is animating and 0 after it finished. The input value is clamped, the functionality of the function I'm looking for is like a switch. It would be a substitute for a complex if statement. Executed in a loop I'm trying to save resources by not using performance heavy if statements.

Looking forward to your input!

sketch

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is what I came up with in the end. Not sure if this is helpful to anyone else. It converts any value between 0 and 1 to 1. But if the input value is equal to 0 or the input value is equal to 1, the function will return 0 as well.

Resulting in the loopback / switch behavior. It returns 1 only whilst a value is progressing. Hope this makes sense and is correct. Happy to hear your thoughts.

Also happy to hear some further thoughts on if such a function is more performant than an if-statement.

In the end I had to solve this to prove to myself that it's possible to do with math. (of course it is):)

const loopback = (i, m = 100) => {
    //returns 1 while value is progressing, returns 0 if value is 0 or 1
    //based on triangle wave function: https://discourse.processing.org/t/sawtooth-wave-algorithm/27433
    i = clamp(i) //normalize value to 0-1
    return Math.ceil(Math.abs((i*(m)) % (m)) / m)
}


const clamp = (number, min = 0, max = 1) => {
    return Math.max(min, Math.min(number, max));
}

//in my usecase, this is an alternative to following condition:
/*if(i >= 1 || i <= 0) {
  return 0;
} else {
  return 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