elena1234

Objects and classes- important exercise ( JavaScript )

Nov 18th, 2021 (edited)
271
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 (!isValid(username) || !isValid(salary) || !isValid(position) || !isValid(department) || salary < 0) {
  8.             throw new Error("Invalid input!");
  9.         }
  10.  
  11.         if (!this.departments[department]) {
  12.             this.departments[department] = [];
  13.             this.departments[department].push({ username, salary, position });
  14.         } else {
  15.             this.departments[department].push({ username, salary, position });
  16.         }
  17.         return `New employee is hired. Name: ${username}. Position: ${position}`;
  18.  
  19.         function isValid(value) {
  20.             if (value === '' || value === undefined || value === null) {
  21.                 return false;
  22.             }
  23.             return true;
  24.         }
  25.     }
  26.  
  27.     bestDepartment() {
  28.         let maxSalary = 0;
  29.         let bestDepartmentWithMaxSalary;
  30.         for (const departmentsName in this.departments) {
  31.             let totalSalaryInDepartment = this.departments[departmentsName].map(employee => employee.salary).reduce((a, b) => a + b, 0);
  32.             let averageSalaryInDepartment = totalSalaryInDepartment / this.departments[departmentsName].length;
  33.             if (averageSalaryInDepartment > maxSalary) {
  34.                 maxSalary = averageSalaryInDepartment;
  35.                 bestDepartmentWithMaxSalary = departmentsName;
  36.             }
  37.         }
  38.  
  39.         let sortedBestDepartment = this.departments[bestDepartmentWithMaxSalary].sort((a, b) => a.username.localeCompare(b.username))
  40.             .sort((a, b) => b.salary - a.salary);
  41.         let result = `Best Department is: ${bestDepartmentWithMaxSalary}\n`;
  42.         result += `Average salary: ${maxSalary.toFixed(2)}\n`;
  43.         result += sortedBestDepartment
  44.             .map(obj => Object.values(obj).join(' '))
  45.             .join('\n');
  46.         return result
  47.     }
  48. }
  49.  
  50.  
  51. let c = new Company();
  52. c.addEmployee("Stanimir", 2000, "engineer", "Construction");
  53. c.addEmployee("Pesho", 1500, "electrical engineer", "Construction");
  54. c.addEmployee("Slavi", 500, "dyer", "Construction");
  55. c.addEmployee("Stan", 2000, "architect", "Construction");
  56. c.addEmployee("Stanimir", 1200, "digital marketing manager", "Marketing");
  57. c.addEmployee("Pesho", 1000, "graphical designer", "Marketing");
  58. c.addEmployee("Gosho", 1350, "HR", "Human resources");
  59. console.log(c.bestDepartment());
  60.  
Add Comment
Please, Sign In to add comment