merging in barrier ... soon to be after

This commit is contained in:
Jeremy Ashkenas
2011-04-15 16:13:51 -04:00
2 changed files with 26 additions and 0 deletions

View File

@@ -137,4 +137,22 @@ $(document).ready(function() {
equals(composed('moe'), 'hi: moe!', 'in this case, the functions are also commutative');
});
test("functions: barrier", function() {
var testBarrier = function(barrierAmount, timesCalled) {
var barrierCalled = 0;
var barrier = _.barrier(function(){ barrierCalled++; }, barrierAmount);
while (timesCalled--) {
barrier();
}
return barrierCalled;
}
equals(testBarrier(5, 5), 1, "barrier(N) should fire after being called N times");
equals(testBarrier(5, 4), 0, "barrier(N) should not fire unless called N times");
equals(testBarrier(5, 6), 1, "barrier(N) should fire only once even if called more than N times");
});
});

View File

@@ -510,6 +510,14 @@
};
};
// Returns a function that will only be executed after being called N times.
_.barrier = function(func, times) {
return function() {
if (--times === 0) { return func.apply(this, arguments); }
};
};
// Object Functions
// ----------------