-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoursera.js
More file actions
39 lines (36 loc) · 1.11 KB
/
Coursera.js
File metadata and controls
39 lines (36 loc) · 1.11 KB
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
// Good example for observer designer pattern
class Coursera {
constructor() {
this.subscribeList = new Map();
this.subscribeOnceList = new Map();
this.subscribeOnceAsyncList = new Map();
}
subscribe(name, callback) {
if (!this.subscribeList.has(name)) {
this.subscribeList.set(name, [callback]);
} else {
const callBackList = this.subscribeList.get(name);
this.subscribeList.set(name, [...callBackList, callback]);
}
return () => {
this.remove(name, callback);
};
}
remove(name, callback) {
const callBackList = this.subscribeList.get(name);
const callBackListFiltered = callBackList.filter((callbackList) => {
callbackList !== callback;
});
this.subscribeList.set(name, callBackListFiltered);
}
subscribeOnceAsync(name) {
return new Promise((resolve) => {
if (!this.subscribeOnceAsyncList.has(name)) {
this.subscribeOnceAsyncList.set(name, [resolve]);
} else {
const callBackList = this.subscribeList.get(name);
this.subscribeOnceAsyncList.set(name, [...callBackList, resolve]);
}
});
}
}