kstoyanov

01. Company

Oct 6th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Company {
  2.   constructor() {
  3.     this.departments = [];
  4.   }
  5.  
  6.   addEmployee(...args) {
  7.     const [username, salary, position, department] = args;
  8.  
  9.     const isInvalidInput = args.some((empl) => empl === null || empl === undefined || empl === '') || salary < 0;
  10.  
  11.     if (isInvalidInput) {
  12.       throw new Error('Invalid input!');
  13.     } else {
  14.       const newEmployee = {
  15.         username,
  16.         salary,
  17.         position,
  18.         department,
  19.       };
  20.  
  21.       if (this.departments.filter((e) => e.name === department).length > 0) {
  22.         for (const existingDepartment of this.departments) {
  23.           if (existingDepartment.name === department) {
  24.             existingDepartment.users.push(newEmployee);
  25.             existingDepartment.totalSalary += salary;
  26.           }
  27.         }
  28.       } else {
  29.         const newDepartment = {
  30.           name: department,
  31.           users: [newEmployee],
  32.           totalSalary: salary,
  33.           averageSalary() {
  34.             return this.totalSalary / this.users.length;
  35.           },
  36.         };
  37.  
  38.         this.departments.push(newDepartment);
  39.       }
  40.  
  41.       return `New employee is hired. Name: ${username}. Position: ${position}`;
  42.     }
  43.   }
  44.  
  45.   bestDepartment() {
  46.     const bestDepartment = this.departments.sort((a, b) => a.averageSalary - b.averageSalary)[0];
  47.  
  48.     bestDepartment.users = bestDepartment.users.sort((a, b) => {
  49.       if (a.username === b.username) {
  50.         return b.username - a.username;
  51.       }
  52.       return a.salary < b.salary ? 1 : -1;
  53.     });
  54.  
  55.     let result = `Best Department is: ${bestDepartment.name}\nAverage salary: ${bestDepartment.averageSalary().toFixed(2)}`;
  56.  
  57.     for (const user of bestDepartment.users) {
  58.       result += `\n${user.username} ${user.salary} ${user.position}`;
  59.     }
  60.  
  61.     return result;
  62.   }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment