concept generator in category coffeescript

appears as: generators, A generator, generator
CoffeeScript in Action

This is an excerpt from Manning's book CoffeeScript in Action.

A note on generators

Future versions of JavaScript (and by extension CoffeeScript) will include something called generators (discussed in chapter 13) that will make comprehensions a more powerful general programming tool. Until that day, though, limit comprehensions to expressing set relationships and use more general-purpose programming constructs, such as functions, elsewhere.

CoffeeScript will need to add new syntax to support the yield keyword for generators. One option is the starred arrow ->*:

keyboardEventGenerator = ->*
  while true
    if Math.floor Math.random()*10 > 5
      yield UP
    else
      yield DOWN

At the time of writing, the actual syntax hasn’t been decided and CoffeeScript doesn’t currently support generators. Both the ECMAScript 6 specification and the CoffeeScript syntax to deal with it are still evolving.

A generator is like a function, but instead of just being evaluated, it can suspend execution and resume later. Being able to yield in the middle of a function means that the generator and the function that uses it work together. With regular functions, a function invocation always completes before the calling function resumes. In contrast, with generators, the calling function gets control back many times. That’s why generator functions are sometimes known as co-routines in languages where the equivalents of functions are known as routines.

Will these generators be useful in CoffeeScript? Absolutely. They’ll be useful in all those places where you’ve either ended up with event-emitter spaghetti code or have created your own abstraction to deal with them. Generators and comprehensions will give you more syntactic flexibility.