forked from cujojs/when
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunfold.js
More file actions
41 lines (34 loc) · 1.22 KB
/
unfold.js
File metadata and controls
41 lines (34 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/** @license MIT License (c) copyright B Cavalier & J Hann */
/**
* unfold
* @author: brian@hovercraftstudios.com
*/
(function(define) {
define(function(require) {
var when = require('./when');
/**
* Anamorphic unfold/map that generates values by applying
* handler(generator(seed)) iteratively until condition(seed)
* returns true.
* @param {function} unspool function that generates a [value, newSeed]
* given a seed.
* @param {function} condition function that, given the current seed, returns
* truthy when the unfold should stop
* @param {function} handler function to handle the value produced by generator
* @param seed {*|Promise} any value or promise
* @return {Promise} the result of the unfold
*/
return function unfold(unspool, condition, handler, seed) {
return when(seed, function(seed) {
return when(condition(seed), function(done) {
return done ? seed : when.resolve(unspool(seed)).spread(next);
});
function next(item, newSeed) {
return when(handler(item), function() {
return unfold(unspool, condition, handler, newSeed);
});
}
});
};
});
})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); } );