diff options
Diffstat (limited to 'src/utils.clj')
| -rwxr-xr-x | src/utils.clj | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/utils.clj b/src/utils.clj index b315bb3..7f56f61 100755 --- a/src/utils.clj +++ b/src/utils.clj @@ -370,3 +370,31 @@ "Evaluates expr if user is super-vip otherwise returns 404. Can only be used where session is defined." `(if (is-super-vip? ~'session) ~e (unknown-page))) + + +;; Time-expiry memoize +;; http://www.mail-archive.com/clojure@googlegroups.com/msg20038.html + +(defn expire-cached-results* [cached-results time-to-live] + "Expire items from the cached function results." + (into {} + (filter (fn [[k v]] + (> time-to-live + (- (System/currentTimeMillis) (:time v)))) cached-results))) + +(defn ttl-memoize + "Returns a memoized version of a referentially transparent function. The + memoized version of the function keeps a cache of the mapping from arguments + to results and, when calls with the same arguments are repeated often, has + higher performance at the expense of higher memory use. Cached results are + removed from the cache when their time to live value expires." + [function time-to-live] + (let [cached-results (atom {})] + (fn [& arguments] + (swap! cached-results expire-cached-results* time-to-live) + (if-let [entry (find @cached-results arguments)] + (:result (val entry)) + (let [result (apply function arguments)] + (swap! cached-results assoc arguments + { :result result :time (System/currentTimeMillis)}) + result)))))
\ No newline at end of file |
