Guest User

Untitled

a guest
Jun 23rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. // Some generator fun!
  2.  
  3. // WORK IN PROGRESS
  4. // Only accepts two arguments in the `cb` call for the moment
  5.  
  6. "use strict";
  7. const cbOnPrev = ((reset) => Object.defineProperty(
  8. function* cbOnPrev (cb) {
  9. let a = yield; // Replace `yield` with `function.sent` once it's a thing
  10. let b = yield a;
  11.  
  12. while (true) {
  13. [a, b] = [b, yield cb(a, b)];
  14. if (b === reset) {
  15. a = yield;
  16. b = yield a;
  17. }
  18. }
  19. },
  20. "reset",
  21. { value: reset }
  22. ))(Symbol("reset"));
  23.  
  24.  
  25. // Usage
  26.  
  27. // Kinda Fibonacci
  28. const fibIt = cbOnPrev((n1, n2) => n1 + n2);
  29.  
  30. fibIt.next(); // Remove this step once function.sent is a thing
  31.  
  32. let fibNum = 1; // Starting at 0 would infini-loop!
  33.  
  34. while (fibNum < 100) {
  35. fibNum = fibIt.next(fibNum).value;
  36. console.log(fibNum);
  37. }
  38. // Close if you want to
  39. fibIt.return(fibNum);
  40.  
  41. // Reset with
  42. /*
  43. fibIt.next(cbOnPrev.reset);
  44. fibIt.next();
  45. */
Add Comment
Please, Sign In to add comment