diff --git a/test/functions.js b/test/functions.js index 83c69d730..77ad72b39 100644 --- a/test/functions.js +++ b/test/functions.js @@ -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"); + }); + }); diff --git a/underscore.js b/underscore.js index e142ec90c..a45ca8907 100644 --- a/underscore.js +++ b/underscore.js @@ -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 // ----------------