UNPKG

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