Skip to contents

Wraps f so that repeated calls with the same arguments return a cached value. This is a thin facade over memoise::memoise() backed by cachem::cache_mem(): memoise hashes arguments internally, and cache_mem provides LRU eviction (.max_size) and time-to-live (.ttl).

Usage

with_cache(f, ..., .max_size = Inf, .ttl = Inf)

Arguments

f

A function to wrap.

...

Reserved for future extension.

.max_size

Maximum number of cached entries. Inf (default) for unbounded; when exceeded, least-recently-used entries are evicted.

.ttl

Time-to-live in seconds for cached entries. Inf (default) never expires.

Value

A function that forwards its arguments to f. Attach cache_clear() and cache_info() helpers via cache_clear() and cache_info().

Examples

# \donttest{
calls <- 0
slow <- function(x) {
  calls <<- calls + 1
  x * 2
}
fast <- with_cache(slow)
fast(21)
#> [1] 42
fast(21)
#> [1] 42
calls
#> [1] 1
# }