UNPKG

2.78 kBJavaScriptView Raw
1import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
2import _createClass from 'babel-runtime/helpers/createClass';
3/*
4Copyright 2013-2015 ASIAL CORPORATION
5
6Licensed under the Apache License, Version 2.0 (the "License");
7you may not use this file except in compliance with the License.
8You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12Unless required by applicable law or agreed to in writing, software
13distributed under the License is distributed on an "AS IS" BASIS,
14WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15See the License for the specific language governing permissions and
16limitations under the License.
17
18*/
19
20var generateId = function () {
21 var i = 0;
22 return function () {
23 return i++;
24 };
25}();
26
27/**
28 * Door locking system.
29 *
30 * @param {Object} [options]
31 * @param {Function} [options.log]
32 */
33
34var 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 * Register a lock.
47 *
48 * @return {Function} Callback for unlocking.
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 * Register a callback for waiting unlocked door.
89 *
90 * @params {Function} callback Callback on unlocking the door completely.
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 * @return {Boolean}
109 */
110
111 }, {
112 key: 'isLocked',
113 value: function isLocked() {
114 return this._lockList.length > 0;
115 }
116 }]);
117
118 return DoorLock;
119}();
120
121export default DoorLock;
\No newline at end of file