Guest User

Company

a guest
Jun 14th, 2020
356
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(username, salary, position, department) {
  7.         if ([...arguments].some(a => a === null || a === undefined || a === '') || salary < 0) {
  8.             throw new Error('Invalid input!');
  9.         } else {
  10.             const newEmployee = {
  11.                 username: username,
  12.                 salary: salary,
  13.                 position: position,
  14.                 department: department,
  15.             };
  16.             if (this.departments.filter(function (e) {return e.name === department;}).length > 0) {
  17.                 for (let existingDepartment of this.departments) {
  18.                     if (existingDepartment.name === department) {
  19.                         existingDepartment.users.push(newEmployee);
  20.                         existingDepartment.totalSalary += salary;
  21.                     }
  22.                 }
  23.             } else {
  24.                 let newDepartment = {
  25.                     name: department,
  26.                     users: [newEmployee],
  27.                     totalSalary: salary,
  28.                     averageSalary() {
  29.                         return this.totalSalary / this.users.length;
  30.                     },
  31.                 };
  32.                 this.departments.push(newDepartment);
  33.             }
  34.             return `New employee is hired. Name: ${username}. Position: ${position}`;
  35.         }
  36.     }
  37.  
  38.     bestDepartment() {
  39.         let bestDepartment = this.departments.sort((a, b) => a.averageSalary - b.averageSalary)[0];
  40.         bestDepartment.users = bestDepartment.users.sort(function (a, b) {
  41.             if (a.username === b.username) {
  42.                 // Price is only important when cities are the same
  43.                 return b.username - a.username;
  44.             }
  45.             return a.salary < b.salary ? 1 : -1;
  46.         });
  47.         let result = `Best Department is: ${bestDepartment.name}\nAverage salary: ${bestDepartment.averageSalary().toFixed(2)}`;
  48.         for (let user of bestDepartment.users) {
  49.             result += `\n${user.username} ${user.salary} ${user.position}`;
  50.         }
  51.         return result;
  52.     }
  53. }
Add Comment
Please, Sign In to add comment