git ssb

2+

Dominic / pull-stream



Tree: 29e58b56a883059f89ae1af0c648b8bbfea64f2b

Files: 29e58b56a883059f89ae1af0c648b8bbfea64f2b / sinks.js

2173 bytesRaw
1'use strict'
2
3function id (item) { return item }
4
5function prop (key) {
6 return (
7 'string' == typeof key
8 ? function (data) { return data[key] }
9 : 'object' === typeof key && 'function' === typeof key.exec //regexp
10 ? function (data) { var v = map.exec(data); return v && v[0] }
11 : key || id
12 )
13}
14
15
16var drain = exports.drain = function (op, done) {
17
18 return function (read) {
19
20 //this function is much simpler to write if you
21 //just use recursion, but by using a while loop
22 //we do not blow the stack if the stream happens to be sync.
23 ;(function next() {
24 var loop = true, cbed = false
25 while(loop) {
26 cbed = false
27 read(null, function (end, data) {
28 cbed = true
29 if(end) {
30 loop = false
31 if(done) done(end === true ? null : end)
32 else if(end && end !== true)
33 throw end
34 }
35 else if(op && false === op(data)) {
36 loop = false
37 read(true, done || function () {})
38 }
39 else if(!loop){
40 next()
41 }
42 })
43 if(!cbed) {
44 loop = false
45 return
46 }
47 }
48 })()
49
50 }
51}
52
53var onEnd = exports.onEnd = function (done) {
54 return drain(null, done)
55}
56
57var log = exports.log = function (done) {
58 return drain(function (data) {
59 console.log(data)
60 }, done)
61}
62
63var find =
64exports.find = function (test, cb) {
65 var ended = false
66 if(!cb)
67 cb = test, test = id
68 else
69 test = prop(test) || id
70
71 return drain(function (data) {
72 if(test(data)) {
73 ended = true
74 cb(null, data)
75 return false
76 }
77 }, function (err) {
78 if(ended) return //already called back
79 cb(err === true ? null : err, null)
80 })
81}
82
83var reduce = exports.reduce = function (reduce, acc, cb) {
84
85 return drain(function (data) {
86 acc = reduce(acc, data)
87 }, function (err) {
88 cb(err, acc)
89 })
90
91}
92
93var collect = exports.collect =
94function (cb) {
95 return reduce(function (arr, item) {
96 arr.push(item)
97 return arr
98 }, [], cb)
99}
100
101var concat = exports.concat =
102function (cb) {
103 return reduce(function (a, b) {
104 return a + b
105 }, '', cb)
106}
107
108

Built with git-ssb-web