Created
April 2, 2019 20:05
-
-
Save jmakeig/f91b65894ec5ca7a78e4f46a9452d5e3 to your computer and use it in GitHub Desktop.
Wrap a generator to log its output
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
/** | |
* Logs generated values and re-yields them. Keeps the same | |
* signature and behavior as the wrapped geneator. | |
* | |
* @example const myGenerator = logAdvice(function*(…){…}) | |
* | |
* @param {GeneratorFunction} generator The generator to wrap | |
* @param {Function} [filter = () => true] Only log yielded values that evaluate to `true` | |
* @returns {GeneratorFunction} A generator that can be called exactly like the one passed in | |
*/ | |
function logAdvice(generator, filter = () => true) { | |
return function* logAdviceWrapper(...rest) { | |
for (const y of generator(...rest)) { | |
if (filter(y)) { | |
console.log(y); | |
// Get stacktrace | |
// console.log(new Error().stack); | |
} | |
yield y; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment