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

163
Views
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 answers
Answer question

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