Last active
August 29, 2015 14:26
-
-
Save therne/3e928953c69cb0d02718 to your computer and use it in GitHub Desktop.
GeneratorFunctionBuilder - Builds new generator function with code.
This file contains 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
var builder = new GeneratorFunctionBuilder('param1', 'param2'); | |
var Func = builder | |
.append('var ab = %d', 1234) | |
.append('yield param1 + param2'); | |
.build(); | |
/** | |
* It is same with... | |
* function* Func(param1, param2) { | |
* var ab = 1234; | |
* yield param1 + param2; | |
* } | |
*/ |
This file contains 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
'use strict'; | |
var util = require('util'); | |
var GeneratorFunction = (function*(){}).constructor; | |
module.exports = GeneratorFunctionBuilder; | |
/** | |
* Builds new generator function with code. | |
*/ | |
function GeneratorFunctionBuilder() { | |
this.src = ''; | |
this.arguments = []; | |
for (var i in arguments) this.arguments.push(arguments[i]); | |
} | |
GeneratorFunctionBuilder.prototype.append = function() { | |
this.src += util.format.apply(null, arguments) + ';\n'; | |
return this; | |
} | |
GeneratorFunctionBuilder.prototype.build = function() { | |
this.arguments.push(this.src); | |
return GeneratorFunction.apply(null, this.arguments); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment