Quiero preguntar ¿cómo puedo simplificar mi código? Parece difícil de leer y tiene demasiada condición if-else aquí. ¿Alguna forma de simplificar el código?
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; }Simplemente puede separar la condición usando if-else separado
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 }Lo primero que podría hacer es factorizar e.shiftKey y usar los operadores += y -=
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; } }Si alguna vez quieres ir con ternarios:
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 );Tenga en cuenta que esto no es necesariamente más legible, solo ocupa menos espacio.
Puede hacerlo un poco más sucinto usando el hecho de que sus cláusulas if lógicamente se implican entre sí en parte.
si e.shiftKey es true , cambia algo si this.idx es 0 o más y si e.shiftKey es false , cambia algo solo si 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;No es necesariamente mucho más legible.