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

182
Views
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 answers
Answer question

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 Report

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 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!