One of the most powerful feature of ECMA6 is Generator Functions, which is the most favourite topics for interviewers. Generator functions are nothing but, can be exited and later re-entered, where their context will be saved across re-entrances. ie. Can be stopped in Midway and continued from where it is Stopped.
Some of the tricky question asked:
Below section of the post describe all the answers.
Generator object, which confirms to Iterable and Iterator protocol. Used in conjunction with Promises they resolve the problem with Callback Hell and Inversion of Control.
Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead.
When the iterator’s next() method is called, the generator function’s body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function.
The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. { value: Any, done: false | true }
Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where execution was paused with the argument from next().
A return statement in a generator, when executed, will make the generator finish ({ value: Any, done: true }).
If an error thrown inside the generator will make the generator finished – unless caught within the generator’s body.
When a generator is finished, subsequent next calls will not execute any of that generator’s code, they will just return an object of this form: {value: undefined, done: true}.
Interview Tips
function* charGenerator(str) {
for(var i=0; i < str.length; i++) {
yield str[i];
}
}
var str = "United We Stand";
var gen = charGenerator([...str]);
console.log(gen.next()); // Object { value: "U", done: false }
console.log(gen.next()); // Object { value: "i", done: false }
console.log(gen.next()); // Object { value: "n", done: false }
console.log(gen.next()); // Object { value: "t", done: false }
console.log(gen.next()); // Object { value: "e", done: false }
console.log(gen.next()); // Object { value: "d", done: false }
console.log(gen.next()); // Object { value: " ", done: false }
console.log(gen.next()); // Object { value: "W", done: false }
console.log(gen.next()); // Object { value: "e", done: false }
console.log(gen.next()); // Object { value: " ", done: false }
console.log(gen.next()); // Object { value: "S", done: false }
console.log(gen.next()); // Object { value: "t", done: false }
console.log(gen.next()); // Object { value: "a", done: false }
console.log(gen.next()); // Object { value: "n", done: false }
console.log(gen.next()); // Object { value: "d", done: false }
console.log(gen.next()); // Object { value: undefined, done: true }
Some of the True Statements about Generators: