Home > Blockchain >  how can I make this code shorter? there're too many "ifs"
how can I make this code shorter? there're too many "ifs"

Time:06-03

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

CodePudding user response:

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 
}

CodePudding user response:

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)
  • Related