git ssb

16+

Dominic / patchbay



Tree: 1a2e89c1945e9b2330e4834a9e544adbc12b171d

Files: 1a2e89c1945e9b2330e4834a9e544adbc12b171d / util.js

1622 bytesRaw
1var pull = require('pull-stream')
2var Next = require('pull-next')
3
4function first (list, test) {
5 for(var i in list) {
6 var value = test(list[i], i, list)
7 if(value) return value
8 }
9}
10
11function decorate (list, value, caller) {
12 caller = caller || function (d,e,v) { return d(e, v) }
13
14 return list.reduce(function (element, decorator) {
15 return caller(decorator, element, value) || element
16 }, null)
17}
18
19function get(obj, path) {
20 if(obj == null) return obj
21 if('string' === typeof path) return obj[path]
22 for(var i = 0; i < path.length; i++) {
23 obj = obj[path[i]]
24 if(obj == null) return
25 }
26 return obj
27
28}
29
30exports.first = first
31exports.decorate = decorate
32
33exports.next = function (createStream, opts, property, range) {
34
35 range = range || opts.reverse ? 'lt' : 'gt'
36 property = property || 'timestamp'
37
38 var last = null, count = -1
39 return Next(function () {
40 if(last) {
41 if(count === 0) return
42 var value = opts[range] = get(last, property)
43 if(value == null) return
44 last = null
45 }
46 return pull(
47 createStream(opts),
48 pull.through(function (msg) {
49 count ++
50 if(!msg.sync) last = msg
51 }, function (err) {
52 //retry on errors...
53 if(err) return count = -1
54 //end stream if there were no results
55 if(last == null) last = {}
56 })
57 )
58 })
59}
60
61exports.firstPlug = function (plugs) {
62 if(!Array.isArray(plugs)) throw new Error('plugs must be an array')
63 var args = [].slice.call(arguments)
64 var plugs = args.shift()
65 return exports.first(plugs, function (fn) {
66 return fn.apply(null, args)
67 })
68}
69
70

Built with git-ssb-web