-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (65 loc) · 1.86 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
73
74
75
76
77
78
79
/*
Using a JavaScript Proxy, create a wrapper for adding pre-initialization queues to any object.
You should allow the consumer of the wrapper to decide which methods to augment
and the name of the property/event that indicates if the component is initialized.
*/
//Proxy Factory
function proxyFactory (target, handler){
return new Proxy(target, handler)
} // End Proxy Factory
// Proxy Handler
const preInitHandler = {
connected: false,
preInitQueue: [],
execute: function () {
console.log(`Connected and executing`)
this.preInitQueue.forEach(command => command())
this.preInitQueue = []
},
get(target, property){
if(property === 'connect'){
this.connected = true
return (...args)=>this.execute(...args)
}//end if prop == connect
if(property === 'disconnect'){
this.connected = false
}//end if prop == disconnect
if(this.connected){
return (...args)=>target[property](...args)
} //end if connected
console.log(`Not Connected. Queueing Method`)
return (...args)=>{
console.log(`Command Queued:`, property, args)
return new Promise((res,rej)=>{
const command = () => {
target[property](...args)
.then(res,rej)
}
this.preInitQueue.push(command)
}) //End Promise
}// End Final Return
}// End Get Trap
} //End Proxy Handler
/*
Testing
*/
const db = {
launch: (()=>async (arg)=>console.log(arg))()
}
async function launcher(obj,num){
await obj.launch(`Hello${num}`)
}
function main(){
const dbProxy = proxyFactory(db,preInitHandler)
launcher(dbProxy,1)
launcher(dbProxy,2)
dbProxy.connect()
setTimeout(()=>{
launcher(dbProxy,4)
},500)
dbProxy.disconnect()
launcher(dbProxy,3)
//Can not reconnect
// dbProxy.connect()
}
main()