Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Company {
- constructor() {
- this.departments = [];
- }
- addEmployee(...params) {
- let [name, salary, position, department] = params;
- let departmentPresent = false;
- // invalid input test
- const test = (ele) => ele === undefined || ele === null || ele === '';
- let isInvalidInput = params.some(test) || salary < 0;
- if (isInvalidInput) {
- throw new Error('Invalid input!');
- }
- // create new employee
- const empObj = {
- name,
- salary,
- position,
- department,
- };
- // check if department exists
- this.departments.forEach((depObj) => {
- if (depObj.name === department) {
- departmentPresent = true;
- // if department is already present
- // add the new employee to it
- depObj.employees.push(empObj);
- return;
- }
- });
- // if department doesn't exist, add the new one
- if (!departmentPresent) {
- // create new department object
- const departmentObj = {
- name: department,
- // the new employee is the first one in this department
- // so it's the only one in the employees array
- employees: [empObj],
- totalSalary: function () {
- return (
- this.employees.reduce((acc, cur) => {
- return acc + Number(cur.salary);
- }, 0) / this.employees.length
- );
- },
- };
- this.departments.push(departmentObj);
- }
- return `New employee is hired. Name: ${name}. Position: ${position}`;
- }
- bestDepartment() {
- let output = [];
- let name = '';
- // extract the department with the highest salary out
- let bestSalary = this.departments.reduce(
- (highestSalary, currentDepartment) => {
- let currHigh = currentDepartment.totalSalary();
- if (currHigh > highestSalary) {
- // save best department's name and avg salary
- name = currentDepartment.name;
- return currHigh;
- }
- return highestSalary;
- },
- Number.MIN_SAFE_INTEGER
- );
- let nameLine = `Best department is: ${name}`;
- let salaryLine = `Average salary: ${bestSalary.toFixed(2)}`;
- let employeesArr = [];
- this.departments.forEach((department) => {
- if (department.name === name) {
- // find the array containing the best department's employees
- employeesArr = department.employees.map((e) => e);
- }
- });
- // sort by highest salary descending
- // sort by name
- employeesArr.sort((eA, eB) => {
- return eB.salary - eA.salary || eA.name.localeCompare(eB.name);
- });
- // add to output arr
- output.push(nameLine);
- output.push(salaryLine);
- output = output.concat(
- employeesArr.map((e) => `${e.name} ${e.salary} ${e.position}`)
- );
- return output.join('\n').trim();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement