Files: 2b8ed0b778ffe06dbf19898b0cdeb8e009224087 / throughs / take.js
981 bytesRaw
1 | |
2 | |
3 | //read a number of items and then stop. |
4 | module.exports = function take (test, opts) { |
5 | opts = opts || {} |
6 | var last = opts.last || false // whether the first item for which !test(item) should still pass |
7 | var ended = false |
8 | if('number' === typeof test) { |
9 | last = true |
10 | var n = test; test = function () { |
11 | return --n |
12 | } |
13 | } |
14 | |
15 | return function (read) { |
16 | |
17 | function terminate (cb) { |
18 | read(true, function (err) { |
19 | last = false; cb(err || true) |
20 | }) |
21 | } |
22 | |
23 | return function (end, cb) { |
24 | if(ended) last ? terminate(cb) : cb(ended) |
25 | else if(ended = end) read(ended, cb) |
26 | else |
27 | read(null, function (end, data) { |
28 | if(ended = ended || end) { |
29 | //last ? terminate(cb) : |
30 | cb(ended) |
31 | } |
32 | else if(!test(data)) { |
33 | ended = true |
34 | last ? cb(null, data) : terminate(cb) |
35 | } |
36 | else |
37 | cb(null, data) |
38 | }) |
39 | } |
40 | } |
41 | } |
42 |
Built with git-ssb-web