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

183
Vistas
how can I make this code shorter? there're too many "ifs"

So ok, this must be pretty simple, but I just can't get it. Should I create some variables and store parts of code there? Or there's a smarter way? I mean conditions are similar and the logic is similar and I'm not quite sure where to start

const comparator = (a: TimeOff, b: TimeOff): number => {
if (order.sortBy === "status" && order.descending) {
  if (a.state === "DECLINED") {
    return -1;
  }
  if (a.state === "APPROVED") {
    return 1;
  }
  return 0;
}
if (order.sortBy === "status" && !order.descending) {
  if (a.state === "DECLINED") {
    return 1;
  }
  if (a.state === "APPROVED") {
    return -1;
  }
  return 0;
}
if (order.sortBy === "dateFrom" && order.descending) {
  if (new Date(a.date_from) < new Date(b.date_from)) {
    return -1;
  }
  if (new Date(a.date_from) > new Date(b.date_from)) {
    return 1;
  }
  return 0;
}
if (order.sortBy === "dateFrom" && !order.descending) {
  if (new Date(a.date_from) < new Date(b.date_from)) {
    return 1;
  }
  if (new Date(a.date_from) > new Date(b.date_from)) {
    return -1;
  }
  return 0;
}}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

let sign;

if (order.sortBy === "status") {
  // Sign will be -1, 0 or 1 (+ operator converts boolean to number, if false then 0, if true 1)
  sign = +(a.state === "APPROVED") - +(a.state === "DECLINED");    
}

if (order.sortBy === "dateFrom") {
  sign = Math.sign(new Date(a.date_from) < new Date(b.date_from));  
}

return sign * (~~order.descending || -1)
about 4 years ago · Juan Pablo Isaza Denunciar

0

const sort = {
  "status": {
    "DECLINED": 1,
    "APPROVED": -1
  },
  "dateFrom":{
    "lessThan": -1,
    "higherThan": 1
  }
}

const comparator = (a, b) => {
  const { sortBy, descending } = order
  const offset = new Date(a.date_from) < new Date(b.date_from) ? "lessThan" : "higherThan"
  const value = sort[sortBy][a.state] || sort[sortBy][offset] || 0

  // multiplying by -1 changes the value from negtive to positive and vice versa
  let result = descending ? value : value * -1
  return result 
}
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