diff --git a/when/when-tests.ts b/when/when-tests.ts index 7cd7e8e45..267493dd5 100644 --- a/when/when-tests.ts +++ b/when/when-tests.ts @@ -116,6 +116,14 @@ when.iterate(function (x) { console.log(err); }); +when.unfold(function (x) { + return [{foo: 'bar'}, x + 1]; +}, function (x) { + return x < 10; +}, function (y) { + delete y.foo; +}, 0); + /* when.promise(resolver) */ promise = when.promise(resolve => resolve(5)); diff --git a/when/when.d.ts b/when/when.d.ts index 432a76b36..a9166ab62 100644 --- a/when/when.d.ts +++ b/when/when.d.ts @@ -141,6 +141,23 @@ declare module When { seed: U | Promise): Promise; + /** + * Similar to when/iterate, when.unfold generates a potentially infinite stream of promises by repeatedly calling + * unspool until predicate becomes true. when.unfold allows you to thread additional state information through the iteration. + * @memberOf when + * @param unspool function that, given a seed, returns a [valueToSendToHandler, newSeed] pair. + * May return an array, array of promises, promise for an array, or promise for an array of promises. + * @param predicate function that receives the current seed, and should return truthy when the unfold should stop + * @param handler function that receives the valueToSendToHandler of the current iteration. + * This function can process valueToSendToHandler in whatever way you need. + * It may return a promise to delay the next iteration of the unfold. + * @param seed initial value provided to the first unspool invocation. May be a promise. + */ + function unfold(unspool: (seed: U) => [T | Promise, U | Promise] | Promise<[T | Promise, U | Promise]>, + predicate: (value: U) => boolean | Promise, + handler: (value: T) => Promise | void, + seed: U | Promise): Promise; + /** * Creates a {promise, resolver} pair, either or both of which * may be given out safely to consumers.