Files: 8b4e456e87cad1c31bf2022137e937fe3a47c2ad / lib / next-stepper.js
952 bytesRaw
1 | const pull = require('pull-stream') |
2 | const Next = require('pull-next') |
3 | var ENDED = {} |
4 | |
5 | module.exports = nextStepper |
6 | |
7 | // TODO - this should be another module? |
8 | |
9 | function nextStepper (createStream, opts, range) { |
10 | range = range || (opts.reverse ? 'lt' : 'gt') |
11 | |
12 | var last = null |
13 | var count = -1 |
14 | |
15 | return Next(function () { |
16 | if (last) { |
17 | if (count === 0) return |
18 | var value = opts[range] = last |
19 | if (value === ENDED) return |
20 | last = null |
21 | } |
22 | return pull( |
23 | createStream(clone(opts)), |
24 | pull.through(function (msg) { |
25 | count++ |
26 | if (!msg.sync) { |
27 | last = msg |
28 | } |
29 | }, function (err) { |
30 | // retry on errors... |
31 | if (err) { |
32 | count = -1 |
33 | return count |
34 | } |
35 | // end stream if there were no results |
36 | if (last == null) last = ENDED |
37 | }) |
38 | ) |
39 | }) |
40 | } |
41 | |
42 | function clone (obj) { |
43 | var _obj = {} |
44 | for (var k in obj) _obj[k] = obj[k] |
45 | return _obj |
46 | } |
47 |
Built with git-ssb-web