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

121
Views
Simplifying IF/ELSE condition

I want to ask how can I simplify my code? It seems hard to read and has too much if-else condition here. Any way to simplify the code?

if (e.shiftKey && this.idx > 0) {
  this.idx= this.idx - 1;
} else if (!e.shiftKey && this.idx < trapFocus.length - 1) {
  this.idx = this.idx + 1;
} else if (!e.shiftKey && this.idx < trapFocus.length + 1) {
  this.idx= this.idx - 2;
} else if (e.shiftKey && this.idx > - 1) {
  this.idx= this.idx + 2;
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can simply separate the condition using separate if-else

if (e.shiftKey){
  if(this.idx > 0) this.idx = this.idx - 1;
  else if(this.idx > -1) this.idx = this.idx + 2;
} else {
  if(this.idx < trapFocus.length - 1)) this.idx = this.idx + 1;
  else if(this.idx < trapFocus.length + 1) this.idx < trapFocus.length + 1
}
about 4 years ago · Juan Pablo Isaza Report

0

This first thing you could do is to factor out e.shiftKey and use += and -= operators

if(e.shiftKey)
{
    if(this.idx > 0)
    {
        this.idx -= 1;
    }
    else if(this.idx > -1)
    {
        this.idx += 2;
    }
}
else{
    if(this.idx < trapFocus.length - 1)
    {
        this.idx += 1;
    }
    else if(this.idx < trapFocus.length + 1)
    {
        this.idx -= 2;
    }
}

If you ever want to go with ternaries:

this.idx += e.shiftKey ? (
        this.idx > 0 ? -1 :
        this.idx > -1 ? 2 : 0
    ) : (
        this.idx < trapFocus.length - 1 ? 1 :
        this.idx < trapFocus.length + 1 ? -2 : 0
    );

Note that this is not necessarily more readable, it just takes up less space.

about 4 years ago · Juan Pablo Isaza Report

0

You can get it a bit more succinct by using the fact that your if clauses logically imply each other partly.

if e.shiftKey is true you change something if this.idx is 0 or more and if e.shiftKey is false you change something only if this.idx < trapFocus.length + 1:

let offset = 0;
if (e.shiftKey){
    if (this.idx >= 0) (this.idx ? offset = -1 : offset = 2)  
} else {
    if (this.idx < trapFocus.length + 1) 
       (this.idx < trapFocus.length - 1 ? offset = 1 : offset = -2)
}
this.idx += offset;

It is not necessarily much more readable.

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!