Hemanth's Scribes

javascript

Immediately-Invoked Generator Function Expression (IIGFE)

Author Photo

Hemanth HM

You’ve heard of IIFEs, here’s an interesting pattern I derived when playing with ES6 generators - the Immediately-Invoked Generator Function Expression (IIGFE):

pow = (function *() {
  return Math.pow((yield "x"), (yield "y"));
}());

pow.next();   // { value: "x", done: false }
pow.next(2);  // { value: "y", done: false }
pow.next(3);  // { value: 8, done: true }

The generator is immediately invoked and returns an iterator that you can interact with step by step, passing in values at each yield point.

#javascript#es6#generators