Currently I use Transcrypt to generate Javascript code from Python code. In this way I'm able to implement generators in Python like:
def color():
colors = ["red", "blue", "yellow"]
i = -1
while True:
i += 1
if i >= colors.length:
i = 0
reset = yield colors[i]
if reset:
i = -1
gen = color()
console.log(next(gen)) # red
console.log(gen.js_next(True).value) # red
console.log(next(gen)) # blue
console.log(next(gen)) # yellow
console.log(next(gen)) # red
which will be compiled to Javascript like:
var color = function* () {
var colors = list (['red', 'blue', 'yellow']);
var i = -(1);
while (true) {
i++;
if (i >= colors.length) {
var i = 0;
}
var reset = yield colors [i];
if (reset) {
var i = -(1);
}
}
};
var gen = color ();
console.log (py_next (gen));
console.log (gen.next (true).value);
console.log (py_next (gen));
console.log (py_next (gen));
console.log (py_next (gen));
But since I have also Scala knowledge (and an Scala-application which I would like to implement in the browser) I'm looking to Scala.js. But as far as I know this generator construct is not possible in Scala, and the corresponding yield
keyword is used in a different way.
Is the generator syntax possible in Scala.js, or am I forced to use Python and Transcrypt if I want this?
I believe the general concept you are looking for is Continuations. It's a fairly large and complex topic unto itself -- they used to be talked about more, but have largely been supplanted by the easier-to-use async library. But the scala-continuations library is still around, and discussed various places online -- for example, this article, or this one.