Guest User

Untitled

a guest
Jan 22nd, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. const Stack = (() => {
  2. let items = [];
  3.  
  4. class PublicStack {
  5. peek() {
  6. if (this.isEmpty()) throw new Error("Stack is empty");
  7. const lastItemIndex = items.length - 1;
  8.  
  9. return items[lastItemIndex];
  10. }
  11.  
  12. pop() {
  13. if (this.isEmpty()) throw new Error("Stack is empty");
  14.  
  15. return items.pop();
  16. }
  17.  
  18. push(data) {
  19. items.push(data);
  20. }
  21.  
  22. isEmpty() {
  23. return this.size() === 0;
  24. }
  25.  
  26. size() {
  27. return items.length;
  28. }
  29. }
  30.  
  31. return PublicStack;
  32. })();
  33.  
  34. const nextGreaterElement = (list, element) => {
  35. //creates a stack that only receives the elements that is located after the current element
  36. let elementsAfterStack = new Stack();
  37.  
  38. //controls which elements will be added in element
  39. let startAdding = false;
  40.  
  41. //loops the list to check what's the elements after the current element
  42. list.forEach(currentElement => {
  43. // this is runnned before to avoid add the searched number in elementsAfterStack
  44. if (startAdding) {
  45. elementsAfterStack.push(currentElement);
  46. }
  47.  
  48. // case the current element inside the loop be the same searched element sets the start adding to true, with this the numbers in the next interation will be added in stack
  49. if (currentElement === element) {
  50. startAdding = true;
  51. }
  52. });
  53.  
  54. // the number could be not found, that's the reason that we define this number as null before starts the loop
  55. let nextGreaterElementValue = null;
  56.  
  57. /* execute the full loop removing in each interation the top number until there are no numbers inside the stack,
  58. always when some number greater than actual is founded replaces the current nextGreaterElementValue to this */
  59. while (!elementsAfterStack.isEmpty()) {
  60. if (elementsAfterStack.peek() > element) {
  61. nextGreaterElementValue = elementsAfterStack.peek();
  62. }
  63.  
  64. // we need remove this item from the stack, with this in the next interation other item will be checked
  65. elementsAfterStack.pop();
  66. }
  67.  
  68. return nextGreaterElementValue;
  69. };
Add Comment
Please, Sign In to add comment