-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (53 loc) · 1.44 KB
/
index.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
if (typeof Promise !== 'undefined')
pullToPromise.Promise = Promise;
module.exports = pullToPromise;
pullToPromise.binary = binary;
pullToPromise.any = any;
pullToPromise.none = none;
function pullToPromise( ps, expect ){
var source = ps.source || ps;
var specific = typeof expect === 'number';
var any = expect === true;
var expected = specific ? expect : (expect === false ? 0 : 1);
var received = 0;
var data = any || specific ? [] : undefined;
return new pullToPromise.Promise(function( rslv, rjct ){
return read();
function read(){
return source(null, function( end, chunk ){
if (end) {
if (end !== true)
return rjct(end);
if (!any && received < expected)
return rjct(new Error('pull-to-promise ended after '+received+' values expecting '+expected));
return rslv(data);
}
received++;
if (!any && received > expected)
return rjct(new Error('pull-to-promise received '+received+' values expecting '+expected));
if (any || expected > 1) {
data.push(chunk);
} else {
data = chunk;
}
return read();
});
}
});
}
function any( ps ){
return pullToPromise(ps, true);
}
function none( ps ){
return pullToPromise(ps, false);
}
function binary( ps ){
return pullToPromise(ps, true)
.then(toBinary);
}
function toBinary( r ){
if (r.length > 1)
throw new Error('pull-to-promise received '+r.length+' values expecting one or zero');
return r[0];
}