Reputation: 55749
I need a function f
that when applied to function g
, passes through the first call, then short-circuits subsequent calls until the time between subsequent calls is greater than a value.
In plain English: if calls to f
come in like a "machine gun" I want a memoized value to be used, otherwise normal operation should occur.
Is there a word for this kind of function modifier?
var g = () => { /*...*/ };
var h = f(g); // is there an idiomatic term for function `f`
// `h` is now effectively limiting calls through to g
Edit:
Current hacked implementation (untested, doesn't support functions with parameters):
function memoizeByRate(fn, options) {
var lastCallTime = 0, result;
return function() {
var now = +Date.now(), tmpResult;
if((now - lastCallTime) > options.lifetime) {
tmpResult = fn.apply(this, arguments);
if(options.test && options.test(tmpResult)) {
lastCallTime = now; // !
result = tmpResult;
}
}
lastCallTime = now;
return result;
};
}
// "Test harness"
var i = 0;
var f = () => { console.log('call', ++i); }
var g = memoizeByRate(f, { lifetime: 1000 });
g()
g()
g()
setTimeout(g, 1000);
Upvotes: 0
Views: 40
Reputation: 664648
This is called debouncing, in your case with execution of the debounced function on the leading edge. However, that term is usually used for side-effectful functions only, so no result will be returned or even stored, you'll want to add the term memoisation (as you already did). I guess I'd go for debounceWithCache
or memoiseInBursts
.
See What does _.debounce do? and Debouncing and Throttling Explained Through Examples for details.
Upvotes: 1