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

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

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 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