Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. /**
  2. 9) Facebook On-site Question (45mins) - Implement JavaScript's Generator#Next()
  3. Implement a class called Enumerator, which has a method next().
  4. The Enumerator will be initialized with a flat array (e.g. [1,6,8]).
  5. Calling Enumerator.next() will return the subsequent value in the array, until the array is empty and it will return -1.
  6.  
  7. e = new Enumerator([1,6])
  8. e.next() // returns 1
  9. e.next() // returns 6
  10. e.next() // returns -1
  11.  
  12.  
  13. Implement a class called SuperEnumerator, which has a method next().
  14. The SuperEnumerator will be initialized with an array with nested arrays (e.g. [1,6,[3,4],1,[2,[8,3,[4]]]1])
  15. Calling SuperEnumerator.next() will return the subsequent value in the nested array, as though it was flattened, until the array is empty and it will return -1.
  16.  
  17. e = new Enumerator([1,[3,[3,4],4],[1]])
  18. e.next() // returns 1
  19. e.next() // returns 3
  20. e.next() // returns 3
  21. e.next() // returns 4
  22. e.next() // returns 4
  23. e.next() // returns 1
  24. e.next() // returns -1
  25.  
  26. Note: The constructor and next() should have a complexity of O(1).
  27.  
  28.  
  29. */
  30.  
  31.  
  32. function Generator(input) {
  33. const arr = input;
  34. let recurse = null;
  35.  
  36. const getNext = () => {
  37. let nextVal = null;
  38. if (recurse) {
  39. nextVal = recurse.next();
  40. if (nextVal) {
  41. return nextVal
  42. } else {
  43. recurse = null; // recursive generator is done...
  44. }
  45. }
  46. nextVal = arr.shift();
  47. if (typeof nextVal === 'object') {
  48. recurse = new Generator(nextVal);
  49. return recurse.next();
  50. } else {
  51. return nextVal;
  52. }
  53. }
  54.  
  55. return {
  56. next: function() {
  57. return getNext();
  58. }
  59. }
  60. }
  61.  
  62. const test = new Generator([1,[3,[3,4],4],[1]]);
  63. console.log(test.next());
  64. console.log(test.next());
  65. console.log(test.next());
  66. console.log(test.next());
  67. console.log(test.next());
  68. console.log(test.next());
  69. console.log(test.next());
  70. console.log(test.next());
  71. console.log(test.next());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement