iterate.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2. /** @author Brian Cavalier */
  3. /** @author John Hann */
  4. (function(define) { 'use strict';
  5. define(function() {
  6. return function generate(Promise) {
  7. var resolve = Promise.resolve;
  8. Promise.iterate = iterate;
  9. Promise.unfold = unfold;
  10. return Promise;
  11. /**
  12. * @deprecated Use github.com/cujojs/most streams and most.iterate
  13. * Generate a (potentially infinite) stream of promised values:
  14. * x, f(x), f(f(x)), etc. until condition(x) returns true
  15. * @param {function} f function to generate a new x from the previous x
  16. * @param {function} condition function that, given the current x, returns
  17. * truthy when the iterate should stop
  18. * @param {function} handler function to handle the value produced by f
  19. * @param {*|Promise} x starting value, may be a promise
  20. * @return {Promise} the result of the last call to f before
  21. * condition returns true
  22. */
  23. function iterate(f, condition, handler, x) {
  24. return unfold(function(x) {
  25. return [x, f(x)];
  26. }, condition, handler, x);
  27. }
  28. /**
  29. * @deprecated Use github.com/cujojs/most streams and most.unfold
  30. * Generate a (potentially infinite) stream of promised values
  31. * by applying handler(generator(seed)) iteratively until
  32. * condition(seed) returns true.
  33. * @param {function} unspool function that generates a [value, newSeed]
  34. * given a seed.
  35. * @param {function} condition function that, given the current seed, returns
  36. * truthy when the unfold should stop
  37. * @param {function} handler function to handle the value produced by unspool
  38. * @param x {*|Promise} starting value, may be a promise
  39. * @return {Promise} the result of the last value produced by unspool before
  40. * condition returns true
  41. */
  42. function unfold(unspool, condition, handler, x) {
  43. return resolve(x).then(function(seed) {
  44. return resolve(condition(seed)).then(function(done) {
  45. return done ? seed : resolve(unspool(seed)).spread(next);
  46. });
  47. });
  48. function next(item, newSeed) {
  49. return resolve(handler(item)).then(function() {
  50. return unfold(unspool, condition, handler, newSeed);
  51. });
  52. }
  53. }
  54. };
  55. });
  56. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));