Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate JavaScript yield?

Tags:

javascript

One of the new mechanisms available in JavaScript 1.7 is yield, useful for generators and iterators.

This is currently supported in Mozilla browsers only (that I'm aware of). What are some of the ways to simulate this behavior in browsers where it is not available?

like image 522
sworoc Avatar asked Oct 27 '10 20:10

sworoc


People also ask

How does yield work in JavaScript?

The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword. yield can only be called directly from the generator function that contains it.

How do generators work JavaScript?

A generator is a process that can be paused and resumed and can yield multiple values. A generator in JavaScript consists of a generator function, which returns an iterable Generator object.

What is yield delegation in JavaScript?

The yield* expression is used to delegate to another generator or iterable object.


1 Answers

Well you could always write an outer function that initializes variables in a closure and then returns an object that does whatever work you want.

function fakeGenerator(x) {
  var i = 0;
  return {
    next: function() {
      return i < x ? (i += 1) : x;
    }
  };
}

Now you can write:

var gen = fakeGenerator(10);

and then call gen.next() over and over again. It'd be tricky to simulate the "finally" behavior of the "close()" method on real generators, but you might be able to get somewhere close.

like image 89
Pointy Avatar answered Oct 14 '22 14:10

Pointy