组合_.memoize和_.throttle来限制函数调用并在时间窗口内缓存结果?

Yan*_*ves 5 javascript caching underscore.js

使用一个函数,该函数使一个调用链返回一个结果,该结果在Angular模板中一次请求多次.在这些请求期间,结果不会改变,因此在函数内部进行额外调用的开销是不必要的.

是否可以在一定的等待时间内创建一个缓存并返回相同结果的限制函数?

沿着下面的简化示例.

var throttleCache = _.memoizeThrottle(function() {
    return _.now();
}, 100);

_.delay(throttleCache, 0); // now + 0ms
_.delay(throttleCache, 10); // now + 0ms
_.delay(throttleCache, 99); // now + 0ms
_.delay(throttleCache, 101); // now + 101ms
_.delay(throttleCache, 150); // now + 101ms
Run Code Online (Sandbox Code Playgroud)

据我所知,_.memoize缓存结果无限期地基于参数,无法看到自动刷新此缓存的方法.而且_.throttle_.debounce只触发设定限制范围内的功能,但不会返回包含函数的输出.

Tur*_*oHz 2

我使用 _.memoize 方法来扩展它并添加一个 ttl 参数,以在过期时强制重新计算值。

#!/usr/bin/env coffee

_=require 'underscore'

# Memoize an expensive function by storing its results.
# After ttl time, the value will be recomputed

memoinesic = (func, hasher=_.identity, ttl=0)->

    memoize = ()->

        cache = memoize.cache
        key = hasher.apply(@,arguments)
        now = Date.now()

        if !_.has(cache,key) or now>cache[key].expires

            cache[key] = 
                value: func.apply(@,arguments)
                expires: now+ttl

        cache[key].value

    memoize.cache = {}

    memoize

_.mixin(memoinesic:memoinesic)

# Let's try it!

appendToNow = _.memoinesic(
    (x)-> "#{x}:#{Date.now()}",
    null,
    1000
)

logTimedFoo = _.compose console.log,_.partial appendToNow,'foo'

logTimedFoo()

setInterval logTimedFoo,200
Run Code Online (Sandbox Code Playgroud)