Hemanth's Scribes

javascript

Immediately-Invoked Generator Function Expression (IIGFE)

Author Photo

Hemanth HM

Thumbnail

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
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.