Skip to content

Instantly share code, notes, and snippets.

@jixunmoe
Last active July 6, 2017 12:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jixunmoe/6db9a453ab247d46b819 to your computer and use it in GitHub Desktop.
Save jixunmoe/6db9a453ab247d46b819 to your computer and use it in GitHub Desktop.
[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