1 | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
|
2 | import _createClass from 'babel-runtime/helpers/createClass';
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | var generateId = function () {
|
21 | var i = 0;
|
22 | return function () {
|
23 | return i++;
|
24 | };
|
25 | }();
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | var DoorLock = function () {
|
35 | function DoorLock() {
|
36 | var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
37 |
|
38 | _classCallCheck(this, DoorLock);
|
39 |
|
40 | this._lockList = [];
|
41 | this._waitList = [];
|
42 | this._log = options.log || function () {};
|
43 | }
|
44 |
|
45 | |
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | _createClass(DoorLock, [{
|
53 | key: 'lock',
|
54 | value: function lock() {
|
55 | var _this = this;
|
56 |
|
57 | var unlock = function unlock() {
|
58 | _this._unlock(unlock);
|
59 | };
|
60 | unlock.id = generateId();
|
61 | this._lockList.push(unlock);
|
62 | this._log('lock: ' + unlock.id);
|
63 |
|
64 | return unlock;
|
65 | }
|
66 | }, {
|
67 | key: '_unlock',
|
68 | value: function _unlock(fn) {
|
69 | var index = this._lockList.indexOf(fn);
|
70 | if (index === -1) {
|
71 | throw new Error('This function is not registered in the lock list.');
|
72 | }
|
73 |
|
74 | this._lockList.splice(index, 1);
|
75 | this._log('unlock: ' + fn.id);
|
76 |
|
77 | this._tryToFreeWaitList();
|
78 | }
|
79 | }, {
|
80 | key: '_tryToFreeWaitList',
|
81 | value: function _tryToFreeWaitList() {
|
82 | while (!this.isLocked() && this._waitList.length > 0) {
|
83 | this._waitList.shift()();
|
84 | }
|
85 | }
|
86 |
|
87 | |
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 | }, {
|
94 | key: 'waitUnlock',
|
95 | value: function waitUnlock(callback) {
|
96 | if (!(callback instanceof Function)) {
|
97 | throw new Error('The callback param must be a function.');
|
98 | }
|
99 |
|
100 | if (this.isLocked()) {
|
101 | this._waitList.push(callback);
|
102 | } else {
|
103 | callback();
|
104 | }
|
105 | }
|
106 |
|
107 | |
108 |
|
109 |
|
110 |
|
111 | }, {
|
112 | key: 'isLocked',
|
113 | value: function isLocked() {
|
114 | return this._lockList.length > 0;
|
115 | }
|
116 | }]);
|
117 |
|
118 | return DoorLock;
|
119 | }();
|
120 |
|
121 | export default DoorLock; |
\ | No newline at end of file |