Skip to content

Commit

Permalink
allow multiple closes of the gate
Browse files Browse the repository at this point in the history
  • Loading branch information
yosefd committed Aug 18, 2013
1 parent 61c5754 commit bb44f04
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 13 deletions.
22 changes: 11 additions & 11 deletions lib/gatejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@
module.exports = function () {

var count = 0;
var completion = null;
var callbacks = [];

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

// enter the gate.
// returns true if entrance is allowed.
function enter() {
if (!completion) {
if (!callbacks.length) {
count++;
return true;
}
Expand All @@ -30,21 +30,21 @@ module.exports = function () {
throw new Error('exit called while nobody was inside');
}
if (!(--count)) {
if (completion) {
completion();
}
_completion();
}
}

// trigger gate closing.
function close(callback) {
if (completion) {
throw new Error('close was called more than once');
}
callback = callback || function () { };
completion = callback;
callbacks.push(callback || function() {});
if (!count) {
completion();
_completion();
}
}

function _completion() {
if (callbacks.length) {
callbacks.forEach(function(cb){ cb(); });
}
}
}
Expand Down
27 changes: 25 additions & 2 deletions test/gatetest.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ var gate = require('../main').gate;

module.exports = testCase({

enterecloseexit: function (test) {
// close once
test1: function (test) {
var gate1 = gate();
var step = 0;
test.ok(gate1.enter(), 'should be able enter empty gate');
gate1.close(function () {
test.equal(step, 1, 'get clouse completion should come after everybody left');
test.equal(step, 1, 'get close completion should come after everybody left');
step++;
});
test.equal(step, 0, 'gate is not closed when somebody inside');
Expand All @@ -17,5 +18,27 @@ module.exports = testCase({
gate1.exit();
test.equal(step, 2, 'after everybody left, the gate is closed');
test.done();
},

// close twice
test2: function (test) {
var gate1 = gate();
var step = 0;
test.ok(gate1.enter(), 'should be able enter empty gate');
gate1.close(function () {
test.equal(step, 1, 'get close completion should come after everybody left');
step++;
});
// close again
gate1.close(function () {
test.equal(step, 2, 'get cluse completion should come after everybody left');
step++;
});
test.equal(step, 0, 'gate is not closed when somebody inside');
test.ok(!gate1.enter(), 'should not be able to enter into closing gate');
step++;
gate1.exit();
test.equal(step, 3, 'after everybody left, the gate is closed');
test.done();
}
});

1 comment on commit bb44f04

@amitmach
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Please sign in to comment.