Created
February 19, 2015 19:54
-
-
Save allyourcode/fa2e72216579ccf256fb to your computer and use it in GitHub Desktop.
Inspired by gopherjs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!doctype html> | |
| <html> | |
| <head> | |
| <title>Wat</title> | |
| </head> | |
| <body> | |
| <script> | |
| /* Support */ | |
| // @constructor | |
| function Generator(f, yields) { | |
| this._f = f; | |
| } | |
| Generator.prototype = { | |
| start: function() { | |
| return new GeneratorState(this._f, arguments); | |
| } | |
| }; | |
| // @constructor | |
| function GeneratorState(f, arguments) { | |
| this._f = f; | |
| this._locals = []; | |
| for (var i = 0; i < arguments.length; i++) { | |
| this._locals.push(arguments[i]); | |
| } | |
| this._start = 0; | |
| } | |
| GeneratorState.prototype = { | |
| next: function(yield_in) { | |
| var result = this._f.apply( | |
| null, [this._start, this._locals, yield_in]); | |
| this._start++; | |
| return result; | |
| } | |
| }; | |
| // @constructor | |
| function StopIteration() { | |
| } | |
| function yield_() { | |
| ; | |
| } | |
| /* Translation */ | |
| /* | |
| def foo(x, y): | |
| print x | |
| z = x + y | |
| yield z | |
| print x - y | |
| */ | |
| var foo = new Generator(function(x, y) { /* pay no attn to the man behind the curtain */ var start = arguments[0]; locals = arguments[1], next = arguments[2]; x = locals[0]; y = locals[1]; switch (start) { case 0: | |
| console.log(x); | |
| z = x + y; | |
| yield_(z); /* pay no attn... */ return z; case 1: | |
| console.log(x - y); /* pay no attn... */ throw new StopIteration; break; default: asplode(); } | |
| }, 1); | |
| /* Use */ | |
| var f = foo.start(1, 2); | |
| console.log('CONSTRUCTED'); | |
| var z = f.next(); | |
| console.log('next CALLED'); | |
| var caught; | |
| try { | |
| f.next(); | |
| } catch (e) { | |
| console.log('throw ON next CALL'); | |
| caught = e; | |
| } | |
| console.log("z=" + z + " caught instanceof StopIteration=" + (caught instanceof StopIteration)); | |
| </script> | |
| <button onclick="window.location.reload()">Reload</button> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment