javascriptif-statementeslintcyclomatic-complexity

multiple arguments and conditions in a function in javascript


I have a function that return some informations about employees from an object database

I'm facing some complexity ESlint Problems, so i need to find a way to minimize it or find a smart way to do this instead of using a whole set of if statements.

I'm also trying to find a way to something like this: if I have name, I don't need to do the id verification and vice-versa and i just don't know how to do this... 🤦‍♂️

The function must receive as argument an object of options that will determinate how it will behave:

e.g:

getEmployeesCoverage({ name: 'Sharonda' });
getEmployeesCoverage({ name: 'Spry' });
getEmployeesCoverage({ id: '4b40a139-d4dc-4f09-822d-ec25e819a5ad' });

I have 3 conditions:

  1. verify if i receive any arguments e.g name or id is undefined
  2. verify if name exists in database
  3. verify if id exists in database

I tried this:

function getEmployeesCoverage({ name, id }) {

  if (employees.find((employee) => employee.id === id)) {
    return getEmployeeById(id); // 3. verify if id exists in database
  }
  if (
    employees.find((employee) => employee.lastName === name) ||
    employees.find((employee) => employee.firstName === name)
  ) {
    return getEmployeeByName(name); // 2. verify if the name exists in database
  }
  if (!name || !id) { 
    return getAllEmployees(); // 1. verify if i have any args e.g name or id undefined
  } 
  throw new Error('Invalid Information');
}

Solution

  • I resolve that problem by just checking the arguments in the main function:

    function getEmployeesCoverage({ name, id } = {}) {
      if (name) return getEmployeeByName(name);
      if (id) return getEmployeeById(id);
      if (!name || !id) return getAllEmployees();
    }
    

    And then calling the unique job function that verifies if that argument exist in database and if not throw and error.

    function getEmployeeByName(name) {
      if (employees.find((employee) => employee.lastName === name)
      || employees.find((employee) => employee.firstName === name)) {
        const {
          id: employeeId,
          firstName,
          lastName,
          responsibleFor,
        } = employees.find((employee) => employee.lastName === name)
        || employees.find((employee) => employee.firstName === name);
        return {
          id: employeeId,
          fullName: `${firstName} ${lastName}`,
          species: getSpeciesByIds(...responsibleFor).map((animal) => animal.name),
          locations: getSpeciesByIds(...responsibleFor).map((animal) => animal.location),
        };
      }
      throw new Error('Invalid Informations');
    }