Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Coach {
- constructor(id, capacity) {
- this.id = id;
- this.capacity = capacity;
- }
- }
- class Student {
- constructor(id) {
- this.id = id;
- }
- isSame(other) {
- return other.id === this.id;
- }
- }
- class Mentorship {
- constructor(coachId, studentId) {
- this.coachId = coachId;
- this.studentId = studentId;
- }
- isSame(other) {
- return other.coachId === this.coachId && other.studentId === this.studentId;
- }
- }
- const studentsTable = [];
- const coachesTable = [];
- const relationsTable = [];
- const addStudents = (studentsList) => {
- let newStudents = [...studentsList];
- let remainingRelationsCount = relationsTable.length + newStudents.length;
- let remainingCapacity = coachesTable.reduce((sum, current) => sum + current.capacity, 0);
- for (let coach of coachesTable) {
- if (coach.capacity === 0)
- continue;
- const targetRelationsCount = Math.round(remainingRelationsCount * coach.capacity / remainingCapacity);
- let currentRelationsCount = relationsTable.filter(i => i.coachId === coach.id).length;
- for (let [index, student] of newStudents.entries()) {
- if (studentsTable.findIndex(i => i.isSame(student)) === -1) {
- studentsTable.push(student);
- }
- const relation = new Mentorship(coach.id, student.id);
- if (relationsTable.findIndex(i => i.isSame(relation)) === -1) {
- relationsTable.push(relation);
- newStudents[index] = null;
- ++currentRelationsCount;
- if (currentRelationsCount >= targetRelationsCount) {
- break;
- }
- }
- }
- remainingCapacity -= coach.capacity;
- remainingRelationsCount -= currentRelationsCount;
- newStudents = newStudents.filter(i => i !== null);
- }
- if (newStudents.length > 0) {
- throw new Error("There're no enough coaches to support that request!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement