Last active
October 13, 2016 00:51
-
-
Save ryanve/4a68f49c4ea1c98dc6efc5a3f5f378bf to your computer and use it in GitHub Desktop.
Control how many times a function is called
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {Function} f | |
* @param {number} times | |
* @return {Function} | |
* If positive, limited to run only <var>times</var> times. | |
* If negative, prevented being run until called -<var>times</var> times | |
*/ | |
function occur(f, times) { | |
if (times === 1/0) return f | |
times = ~~times | |
var memo | |
return times > 0 ? function() { | |
if (f && times--) memo = f.apply(this, arguments) | |
else f = times = null | |
return memo | |
} : times < 0 ? function() { | |
if (times < 0) return void ++times | |
times = null | |
return f.apply(this, arguments) | |
} : function() {} | |
} | |
module.exports = occur; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment