SHOW:
|
|
- or go back to the newest paste.
| 1 | class Company {
| |
| 2 | constructor() {
| |
| 3 | this.departments = []; | |
| 4 | } | |
| 5 | ||
| 6 | addEmployee(username, salary, position, department) {
| |
| 7 | for (let arg of [username, salary, position, department]) {
| |
| 8 | this.validate(arg); | |
| 9 | } | |
| 10 | ||
| 11 | if (!this.departments[department]) {
| |
| 12 | this.departments[department] = []; | |
| 13 | } | |
| 14 | ||
| 15 | this.departments[department].push({ username, salary, position });
| |
| 16 | ||
| 17 | return `New employee is hired. Name: ${username}. Position: ${position}`;
| |
| 18 | } | |
| 19 | ||
| 20 | bestDepartment() {
| |
| 21 | //department - avg salary | |
| 22 | let departments = {};
| |
| 23 | Object.entries(this.departments).forEach(([department, employees]) => {
| |
| 24 | let totalSalary = employees | |
| 25 | .map((e) => e.salary) | |
| 26 | .reduce((acc, curr) => (acc += curr)); | |
| 27 | ||
| 28 | departments[department] = totalSalary / employees.length; | |
| 29 | }); | |
| 30 | ||
| 31 | let maxSalary = 0; | |
| 32 | let bestDepartment; | |
| 33 | Object.entries(departments).forEach(([department, avgSalary]) => {
| |
| 34 | if (avgSalary > maxSalary) {
| |
| 35 | maxSalary = avgSalary; | |
| 36 | bestDepartment = department; | |
| 37 | } | |
| 38 | }); | |
| 39 | ||
| 40 | let output = `Best Department is: ${bestDepartment}\nAverage salary: ${departments[
| |
| 41 | bestDepartment | |
| 42 | ].toFixed(2)}\n`; | |
| 43 | ||
| 44 | this.departments[bestDepartment] | |
| 45 | .sort( | |
| 46 | (a, b) => b.salary - a.salary || a.username.localeCompare(b.username) | |
| 47 | ) | |
| 48 | .forEach((e) => {
| |
| 49 | output += `${e.username} ${e.salary} ${e.position}\n`;
| |
| 50 | }); | |
| 51 | ||
| 52 | return output.trim(); | |
| 53 | } | |
| 54 | ||
| 55 | validate(value) {
| |
| 56 | if (!value || value < 0) {
| |
| 57 | throw new Error("Invalid input!");
| |
| 58 | } | |
| 59 | } | |
| 60 | } |