Last active
July 6, 2017 12:27
-
-
Save jixunmoe/6db9a453ab247d46b819 to your computer and use it in GitHub Desktop.
[ES6] Bind generator without context.
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
/** | |
* 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; | |
}; | |
} |
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
// 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