-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgates.js
67 lines (53 loc) · 1.5 KB
/
gates.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
const { EventEmitter } = require('events')
const Promise = require('any-promise')
module.exports = function () {
let globalSwitch
let localSwitches = {}
const emitter = new EventEmitter()
const eventToValue = {
open: true,
close: false
}
const eventToMethod = {
open: 'open',
close: 'close'
}
;['open', 'close'].forEach(event => {
const switchValue = eventToValue[event]
emitter.on(event, id => {
if (id) {
localSwitches[id] = switchValue
return
}
globalSwitch = switchValue
localSwitches = {}
})
const method = eventToMethod[event]
emitter[method] = function (id) {
emitter.emit(event, id)
}
})
emitter.isOpen = function isOpen (id) {
return typeof localSwitches[id] === 'boolean' ? localSwitches[id] : globalSwitch
}
emitter.awaitOpen = function awaitOpen (id) {
return emitter.isOpen(id) ? Promise.resolve() : awaitEvent('open', id)
}
emitter.awaitClosed = function awaitClosed (id) {
return emitter.isOpen(id) ? awaitEvent('close', id) : Promise.resolve()
}
emitter.setMaxListeners(Infinity)
return emitter
function awaitEvent (event, id1) {
return new Promise(resolve => {
emitter.on(event, maybeResolve)
function maybeResolve (id2) {
// if id2 is undefined, the globalSwitch is being thrown
if (typeof id2 === 'undefined' || id1 === id2) {
emitter.removeListener(event, maybeResolve)
resolve()
}
}
})
}
}