1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | const generateId = (function() {
|
19 | let i = 0;
|
20 | return function() {
|
21 | return i++;
|
22 | };
|
23 | })();
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | export default class DoorLock {
|
32 |
|
33 | constructor(options = {}) {
|
34 | this._lockList = [];
|
35 | this._waitList = [];
|
36 | this._log = options.log || function() {};
|
37 | }
|
38 |
|
39 | |
40 |
|
41 |
|
42 |
|
43 |
|
44 | lock() {
|
45 | const unlock = () => {
|
46 | this._unlock(unlock);
|
47 | };
|
48 | unlock.id = generateId();
|
49 | this._lockList.push(unlock);
|
50 | this._log('lock: ' + (unlock.id));
|
51 |
|
52 | return unlock;
|
53 | }
|
54 |
|
55 | _unlock(fn) {
|
56 | const index = this._lockList.indexOf(fn);
|
57 | if (index === -1) {
|
58 | throw new Error('This function is not registered in the lock list.');
|
59 | }
|
60 |
|
61 | this._lockList.splice(index, 1);
|
62 | this._log('unlock: ' + fn.id);
|
63 |
|
64 | this._tryToFreeWaitList();
|
65 | }
|
66 |
|
67 | _tryToFreeWaitList() {
|
68 | while (!this.isLocked() && this._waitList.length > 0) {
|
69 | this._waitList.shift()();
|
70 | }
|
71 | }
|
72 |
|
73 | |
74 |
|
75 |
|
76 |
|
77 |
|
78 | waitUnlock(callback) {
|
79 | if (!(callback instanceof Function)) {
|
80 | throw new Error('The callback param must be a function.');
|
81 | }
|
82 |
|
83 | if (this.isLocked()) {
|
84 | this._waitList.push(callback);
|
85 | } else {
|
86 | callback();
|
87 | }
|
88 | }
|
89 |
|
90 | |
91 |
|
92 |
|
93 | isLocked() {
|
94 | return this._lockList.length > 0;
|
95 | }
|
96 | }
|