viligen

company

Jun 12th, 2022
916
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Company {
  2.     constructor() {
  3.         this.departments = {};
  4.         //{department:{employees: [{name:, salary:, position:},...{}],totalSalaries:totalsum }, }
  5.     }
  6.  
  7.     addEmployee(name, salary, position, department) {
  8.         if (
  9.             !name ||
  10.             (!salary && salary !== 0) ||
  11.             !position ||
  12.             !department ||
  13.             salary < 0
  14.         ) {
  15.             throw new Error('Invalid input!');
  16.         }
  17.         if (!this.departments.hasOwnProperty(department)) {
  18.             this.departments[department] = { employees: [], totalSalaries: 0 };
  19.         }
  20.         this.departments[department].employees.push({ name, salary, position });
  21.         this.departments[department].totalSalaries += salary;
  22.         return `New employee is hired. Name: ${name}. Position: ${position}`;
  23.     }
  24.     bestDepartment() {
  25.         let outputText = [];
  26.         let bestDeptName = Object.keys(this.departments).sort(
  27.             (a, b) =>
  28.                 this.departments[b].totalSalaries /
  29.                     this.departments[b].employees.length -
  30.                 this.departments[a].totalSalaries /
  31.                     this.departments[a].employees.length
  32.         )[0];
  33.         let bestDeptAvgSalary =
  34.             this.departments[bestDeptName].totalSalaries /
  35.             this.departments[bestDeptName].employees.length;
  36.         let sortedBestEmployees = this.departments[bestDeptName].employees.sort(
  37.             (a, b) => b.salary - a.salary || a.name.localeCompare(b.name)
  38.         );
  39.  
  40.         outputText.push(`Best Department is: ${bestDeptName}`);
  41.         outputText.push(`Average salary: ${bestDeptAvgSalary.toFixed(2)}`);
  42.         sortedBestEmployees.forEach((empl) => {
  43.             outputText.push(`${empl.name} ${empl.salary} ${empl.position}`);
  44.         });
  45.         return outputText.join('\n');
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment