Advertisement
Guest User

Untitled

a guest
Oct 18th, 2018
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. class Coach {
  2. constructor(id, capacity) {
  3. this.id = id;
  4. this.capacity = capacity;
  5. }
  6. }
  7.  
  8. class Student {
  9. constructor(id) {
  10. this.id = id;
  11. }
  12. isSame(other) {
  13. return other.id === this.id;
  14. }
  15. }
  16.  
  17. class Mentorship {
  18. constructor(coachId, studentId) {
  19. this.coachId = coachId;
  20. this.studentId = studentId;
  21. }
  22. isSame(other) {
  23. return other.coachId === this.coachId && other.studentId === this.studentId;
  24. }
  25. }
  26.  
  27. const studentsTable = [];
  28.  
  29. const coachesTable = [];
  30.  
  31. const relationsTable = [];
  32. const addStudents = (studentsList) => {
  33. let newStudents = [...studentsList];
  34.  
  35. let remainingRelationsCount = relationsTable.length + newStudents.length;
  36. let remainingCapacity = coachesTable.reduce((sum, current) => sum + current.capacity, 0);
  37.  
  38. for (let coach of coachesTable) {
  39. if (coach.capacity === 0)
  40. continue;
  41. const targetRelationsCount = Math.round(remainingRelationsCount * coach.capacity / remainingCapacity);
  42. let currentRelationsCount = relationsTable.filter(i => i.coachId === coach.id).length;
  43.  
  44. for (let [index, student] of newStudents.entries()) {
  45.  
  46. if (studentsTable.findIndex(i => i.isSame(student)) === -1) {
  47. studentsTable.push(student);
  48. }
  49.  
  50. const relation = new Mentorship(coach.id, student.id);
  51. if (relationsTable.findIndex(i => i.isSame(relation)) === -1) {
  52. relationsTable.push(relation);
  53. newStudents[index] = null;
  54.  
  55. ++currentRelationsCount;
  56. if (currentRelationsCount >= targetRelationsCount) {
  57. break;
  58. }
  59. }
  60. }
  61. remainingCapacity -= coach.capacity;
  62. remainingRelationsCount -= currentRelationsCount;
  63. newStudents = newStudents.filter(i => i !== null);
  64. }
  65.  
  66. if (newStudents.length > 0) {
  67. throw new Error("There're no enough coaches to support that request!");
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement