Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. /**
  2. * Given an array of Person objects, returns the root PersonTreeNode (the CEO).
  3. * @param {Person[]} employees - An array of Person objects representing all the employees of the company.
  4. * @returns {PersonTreeNode} The CEO of the organization.
  5. */
  6.  
  7. function generateTree( employees ) {
  8.  
  9. /**
  10. * @ignore
  11. * INSTRUCTIONS:
  12. * 1. ONLY edit this function and nothing else!.
  13. *
  14. * 2. Analyze the Person.js and PersonTreeNode.js files.
  15. *
  16. * 3. Parse the `employees` array and create a single PersonTreeNode
  17. * object representing the CEO (the Person with no `manager`).
  18. * All PersonTreeNode object's `directReports` arrays should contain
  19. * PersonTreeNode's for their direct reports...creating a tree.
  20. *
  21. * 4. Refresh or click the 'Retry Test' button to rerun the test.
  22. *
  23. * Feel free to create any additional functions in this file as needed.
  24. */
  25.  
  26. var ceo = null; // Should be a PersonTreeNode object at the end;
  27.  
  28. // YOUR CODE STARTS HERE
  29. let employeeList = {};
  30.  
  31. // used when adding employee to list and converting name to an id
  32. let mgrNode = {};
  33.  
  34. // chain all the things like an adult
  35. ceo = employees.map((employee) => new PersonTreeNode(employee))
  36.  
  37. // add employe node to employee list
  38. .map((employee) => {
  39. employeeList[employee.person.id] = employee;
  40. mgrNode[employee.person.name] = employee;
  41. return employee;
  42. })
  43.  
  44. // add curret employee to directReports
  45. .map((employee) => {
  46. if (employee.person.manager) {
  47. let mgrId = employee.person.manager.id;
  48. employeeList[mgrId].directReports.push(employee);
  49. }
  50. return employee;
  51. })
  52.  
  53. // find the ceo
  54. .reduce( ( ceoNode, employee ) => (
  55. // rule: cep has no manager(s)
  56. employee.person.manager === null ? employee : ceoNode ), null );
  57.  
  58. // YOUR CODE ENDS HERE
  59.  
  60. return ceo;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement