Added definition and test for when.unfold

This commit is contained in:
Michael Nahkies
2015-10-23 14:49:02 +13:00
parent b70895565d
commit 2af0f2eaf4
2 changed files with 25 additions and 0 deletions

View File

@@ -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<number>(resolve => resolve(5));

17
when/when.d.ts vendored
View File

@@ -141,6 +141,23 @@ declare module When {
seed: U | Promise<U>): Promise<U>;
/**
* 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<T, U>(unspool: (seed: U) => [T | Promise<T>, U | Promise<U>] | Promise<[T | Promise<T>, U | Promise<U>]>,
predicate: (value: U) => boolean | Promise<boolean>,
handler: (value: T) => Promise<any> | void,
seed: U | Promise<U>): Promise<void>;
/**
* Creates a {promise, resolver} pair, either or both of which
* may be given out safely to consumers.