Skip to content

Commit

Permalink
Merge pull request jashkenas#1628 from josephspens/before
Browse files Browse the repository at this point in the history
Add _.before() function to negate _.after()
  • Loading branch information
michaelficarra committed Jun 28, 2014
2 parents 4455270 + ab81574 commit 48fa9d1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 14 deletions.
22 changes: 21 additions & 1 deletion test/functions.js
Expand Up @@ -437,7 +437,7 @@
increment();
equal(num, 1);

equal(increment(), 1, 'stores a memo to the last value')
equal(increment(), 1, 'stores a memo to the last value');
});

test('Recursive onced function.', 1, function() {
Expand Down Expand Up @@ -512,4 +512,24 @@
equal(testAfter(0, 1), 1, 'after(0) should fire when first invoked');
});

test('before', function() {
var testBefore = function(beforeAmount, timesCalled) {
var beforeCalled = 0;
var before = _.before(beforeAmount, function() { beforeCalled++; });
while (timesCalled--) before();
return beforeCalled;
};

equal(testBefore(5, 5), 4, 'before(N) should not fire after being called N times');
equal(testBefore(5, 4), 4, 'before(N) should fire before being called N times');
equal(testBefore(0, 0), 0, 'before(0) should not fire immediately');
equal(testBefore(0, 1), 0, 'before(0) should not fire when first invoked');

var context = {num: 0};
var increment = _.before(3, function(){ return ++this.num; });
_.times(10, increment, context);
equal(increment(), 2, 'stores a memo to the last value');
equal(context.num, 2, 'provides context');
});

})();
29 changes: 16 additions & 13 deletions underscore.js
Expand Up @@ -784,19 +784,6 @@
};
};

// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};

// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
Expand Down Expand Up @@ -833,6 +820,22 @@
};
};

// Returns a function that will only be executed before being called N times.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
}
else func = null;
return memo;
};
};

// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);

// Object Functions
// ----------------

Expand Down

0 comments on commit 48fa9d1

Please sign in to comment.