Guest User

Untitled

a guest
Jul 19th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. // Example Input 1:
  2. let phoneBook = [{name: 'Ann', number: "123-456-7890"}, {name: 'John', number: "234-567-8901"}, {name: 'John', number: "345-678-9012"} ];
  3. // Phone book is alphabetized
  4.  
  5. // ON Soln
  6. // container for match {}
  7. // loop through the array
  8. // find match, save match to container
  9. // return match.number
  10.  
  11. function searchPhoneBookON(book, name) {
  12. if (!book || !name) {
  13. return 'no match found';
  14. }
  15.  
  16. let lastMatch = {};
  17.  
  18. book.forEach(listing => {
  19. if ((listing.name).toLowerCase() === name.toLowerCase()) {
  20. lastMatch = listing;
  21. }
  22. })
  23.  
  24. return lastMatch.number;
  25. }
  26.  
  27. // ON Version Test
  28. console.log('O(N)', 'John', searchPhoneBookON(phoneBook, 'John'));
  29.  
  30. // More optimized solution
  31. // main function
  32. // holder for last match
  33. // run helper function on book
  34. // return info from holder
  35.  
  36. // helper
  37. // find the middle
  38. // check if it matches or if it's higher
  39. // if it matches, save match
  40. // check the right until
  41. // if it's lower
  42. // check the left.
  43.  
  44.  
  45. function sPhoneB(book, name) {
  46. if (!book || !name) {
  47. return 'match not found';
  48. }
  49. let lastMatch = {};
  50. _sPhoneB(book, name);
  51. return lastMatch.number;
  52.  
  53.  
  54. function _sPhoneB(book, name) {
  55. if (book.length === 0 ) {
  56. return;
  57. } else if (book.length === 1) {
  58. let listing = book[0].name;
  59. if (listing.localeCompare(name) === 0) {
  60. lastMatch = book[0];
  61. }
  62. } else {
  63. let middle = Math.floor(book.length/2)
  64.  
  65. let middleName = book[middle].name;
  66.  
  67. if (name.localeCompare(middleName) >= 0) {
  68. if (middleName.localeCompare(name) === 0) {
  69. lastMatch = book[middle];
  70. }
  71. let right = book.slice(middle);
  72. _sPhoneB(right, name);
  73. } else if (name.localeCompare(middleName) < 0) {
  74. let left = book.slice(0, middle);
  75. _sPhoneB(left, name);
  76. }
  77. }
  78. }
  79. }
  80.  
  81. // Log N Test
  82. console.log('log N', 'Ann', sPhoneB(phoneBook, 'Ann'));
Add Comment
Please, Sign In to add comment