Skip to content

Instantly share code, notes, and snippets.

@ryanve
Last active October 13, 2016 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanve/4a68f49c4ea1c98dc6efc5a3f5f378bf to your computer and use it in GitHub Desktop.
Save ryanve/4a68f49c4ea1c98dc6efc5a3f5f378bf to your computer and use it in GitHub Desktop.
Control how many times a function is called
/**
* @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