Skip to content

Instantly share code, notes, and snippets.

@therne
Last active August 29, 2015 14:26
Show Gist options
  • Save therne/3e928953c69cb0d02718 to your computer and use it in GitHub Desktop.
Save therne/3e928953c69cb0d02718 to your computer and use it in GitHub Desktop.
GeneratorFunctionBuilder - Builds new generator function with code.
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;
* }
*/
'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