Skip to content

Commit bb44f04

Browse files
committed
allow multiple closes of the gate
1 parent 61c5754 commit bb44f04

File tree

2 files changed

+36
-13
lines changed

2 files changed

+36
-13
lines changed

lib/gatejs.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@
1010
module.exports = function () {
1111

1212
var count = 0;
13-
var completion = null;
13+
var callbacks = [];
1414

1515
return { enter: enter, exit: exit, close: close };
1616

1717
// enter the gate.
1818
// returns true if entrance is allowed.
1919
function enter() {
20-
if (!completion) {
20+
if (!callbacks.length) {
2121
count++;
2222
return true;
2323
}
@@ -30,21 +30,21 @@ module.exports = function () {
3030
throw new Error('exit called while nobody was inside');
3131
}
3232
if (!(--count)) {
33-
if (completion) {
34-
completion();
35-
}
33+
_completion();
3634
}
3735
}
3836

3937
// trigger gate closing.
4038
function close(callback) {
41-
if (completion) {
42-
throw new Error('close was called more than once');
43-
}
44-
callback = callback || function () { };
45-
completion = callback;
39+
callbacks.push(callback || function() {});
4640
if (!count) {
47-
completion();
41+
_completion();
42+
}
43+
}
44+
45+
function _completion() {
46+
if (callbacks.length) {
47+
callbacks.forEach(function(cb){ cb(); });
4848
}
4949
}
5050
}

test/gatetest.js

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@ var gate = require('../main').gate;
33

44
module.exports = testCase({
55

6-
enterecloseexit: function (test) {
6+
// close once
7+
test1: function (test) {
78
var gate1 = gate();
89
var step = 0;
910
test.ok(gate1.enter(), 'should be able enter empty gate');
1011
gate1.close(function () {
11-
test.equal(step, 1, 'get clouse completion should come after everybody left');
12+
test.equal(step, 1, 'get close completion should come after everybody left');
1213
step++;
1314
});
1415
test.equal(step, 0, 'gate is not closed when somebody inside');
@@ -17,5 +18,27 @@ module.exports = testCase({
1718
gate1.exit();
1819
test.equal(step, 2, 'after everybody left, the gate is closed');
1920
test.done();
21+
},
22+
23+
// close twice
24+
test2: function (test) {
25+
var gate1 = gate();
26+
var step = 0;
27+
test.ok(gate1.enter(), 'should be able enter empty gate');
28+
gate1.close(function () {
29+
test.equal(step, 1, 'get close completion should come after everybody left');
30+
step++;
31+
});
32+
// close again
33+
gate1.close(function () {
34+
test.equal(step, 2, 'get cluse completion should come after everybody left');
35+
step++;
36+
});
37+
test.equal(step, 0, 'gate is not closed when somebody inside');
38+
test.ok(!gate1.enter(), 'should not be able to enter into closing gate');
39+
step++;
40+
gate1.exit();
41+
test.equal(step, 3, 'after everybody left, the gate is closed');
42+
test.done();
2043
}
2144
});

0 commit comments

Comments
 (0)