Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[ES6] Bind generator without context.
/**
* Bind generator with context preserved.
* @param {Generator} fn The generator
* @return {Generator} Generator with arguments bind.
*/
var _bind = function (fn) {
var args = [].slice.call(arguments, 1);
return function * () {
var ir = fn.apply (this, args.concat.apply(args, arguments));
var n;
while (!(next = ir.next()).done)
yield n.value;
};
}
// Or, can be used as extension to Function Prototype:
(function (Generator) {
Function.prototype.bindAlt = function () {
var fn = this;
var args = [].slice.call(arguments);
return fn instanceof Generator ? function * () {
var next, ir = fn.apply (this, args.concat.apply(args, arguments));
while (!(next = ir.next()).done)
yield next.value;
} : function () {
return fn.apply (this, args.concat.apply(args, arguments));
};
};
})((function*(){}).constructor);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.