Skip to content

Instantly share code, notes, and snippets.

@sebmarkbage
Created May 5, 2017 05:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebmarkbage/f39d3bd76138810c0d17bc548ba439a1 to your computer and use it in GitHub Desktop.
Save sebmarkbage/f39d3bd76138810c0d17bc548ba439a1 to your computer and use it in GitHub Desktop.
Lodash Shortout
(function() {
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
let foo = function(defaultArg) {
return 'foo';
};
let shortFoo = shortOut(foo);
let n = shortFoo('bar');
global.result = n;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment