Last active
June 22, 2018 14:44
-
-
Save Phoenix35/c32611ac42ab1ef9009a6554a69fdda3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // Some generator fun! | |
| // WORK IN PROGRESS | |
| // Only accepts two arguments in the `cb` call for the moment | |
| "use strict"; | |
| const cbOnPrev = ((reset) => Object.defineProperty( | |
| function* cbOnPrev (cb) { | |
| let a = yield; // Replace `yield` with `function.sent` once it's a thing | |
| let b = yield a; | |
| while (true) { | |
| [a, b] = [b, yield cb(a, b)]; | |
| if (b === reset) { | |
| a = yield; | |
| b = yield a; | |
| } | |
| } | |
| }, | |
| "reset", | |
| { value: reset } | |
| ))(Symbol("reset")); | |
| // Usage | |
| // Kinda Fibonacci | |
| const fibIt = cbOnPrev((n1, n2) => n1 + n2); | |
| fibIt.next(); // Remove this step once function.sent is a thing | |
| let fibNum = 1; // Starting at 0 would infini-loop! | |
| while (fibNum < 100) { | |
| fibNum = fibIt.next(fibNum).value; | |
| console.log(fibNum); | |
| } | |
| // Close if you want to | |
| fibIt.return(fibNum); | |
| // Reset with | |
| /* | |
| fibIt.next(cbOnPrev.reset); | |
| fibIt.next(); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment