Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- 9) Facebook On-site Question (45mins) - Implement JavaScript's Generator#Next()
- Implement a class called Enumerator, which has a method next().
- The Enumerator will be initialized with a flat array (e.g. [1,6,8]).
- Calling Enumerator.next() will return the subsequent value in the array, until the array is empty and it will return -1.
- e = new Enumerator([1,6])
- e.next() // returns 1
- e.next() // returns 6
- e.next() // returns -1
- Implement a class called SuperEnumerator, which has a method next().
- The SuperEnumerator will be initialized with an array with nested arrays (e.g. [1,6,[3,4],1,[2,[8,3,[4]]]1])
- 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.
- e = new Enumerator([1,[3,[3,4],4],[1]])
- e.next() // returns 1
- e.next() // returns 3
- e.next() // returns 3
- e.next() // returns 4
- e.next() // returns 4
- e.next() // returns 1
- e.next() // returns -1
- Note: The constructor and next() should have a complexity of O(1).
- */
- function Generator(input) {
- const arr = input;
- let recurse = null;
- const getNext = () => {
- let nextVal = null;
- if (recurse) {
- nextVal = recurse.next();
- if (nextVal) {
- return nextVal
- } else {
- recurse = null; // recursive generator is done...
- }
- }
- nextVal = arr.shift();
- if (typeof nextVal === 'object') {
- recurse = new Generator(nextVal);
- return recurse.next();
- } else {
- return nextVal;
- }
- }
- return {
- next: function() {
- return getNext();
- }
- }
- }
- const test = new Generator([1,[3,[3,4],4],[1]]);
- console.log(test.next());
- console.log(test.next());
- console.log(test.next());
- console.log(test.next());
- console.log(test.next());
- console.log(test.next());
- console.log(test.next());
- console.log(test.next());
- console.log(test.next());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement