From da955a4774e83e541e147cb3b9ee0bf56da1ed17 Mon Sep 17 00:00:00 2001 From: phyzical Date: Sun, 13 Feb 2022 17:57:13 +0800 Subject: [PATCH] refector of setEmployeeToJob --- src/Corporation/OfficeSpace.ts | 36 +++++++++------------------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/src/Corporation/OfficeSpace.ts b/src/Corporation/OfficeSpace.ts index dd90304d6..1572ee945 100644 --- a/src/Corporation/OfficeSpace.ts +++ b/src/Corporation/OfficeSpace.ts @@ -174,34 +174,16 @@ export class OfficeSpace { } setEmployeeToJob(job: string, amount: number): boolean { - let unassignedCount = 0; - let jobCount = 0; - for (let i = 0; i < this.employees.length; ++i) { - if (this.employees[i].pos === EmployeePositions.Unassigned) { - unassignedCount++; - } else if (this.employees[i].pos === job) { + let jobCount = this.employees.reduce((acc, employee) => (employee.pos === job ? acc + 1 : acc), 0); + + for (const employee of this.employees) { + if (jobCount == amount) return true + if (employee.pos === EmployeePositions.Unassigned && jobCount <= amount) { + employee.pos = job; jobCount++; - } - } - - if (jobCount == amount) return false; - if ((jobCount + unassignedCount) < amount) return false; - - for (let i = 0; i < this.employees.length; ++i) { - if (this.employees[i].pos === EmployeePositions.Unassigned) { - if (jobCount <= amount) { - this.employees[i].pos = job; - jobCount++; - unassignedCount--; - } - if (jobCount === amount) break; - } else if (this.employees[i].pos === job) { - if (jobCount >= amount) { - this.employees[i].pos = EmployeePositions.Unassigned; - jobCount--; - unassignedCount++; - } - if (jobCount === amount) break; + } else if (employee.pos === job && jobCount >= amount) { + employee.pos = EmployeePositions.Unassigned; + jobCount--; } } if (jobCount !== amount) return false;