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;
}
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
}
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.
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.