Skip to content

Instantly share code, notes, and snippets.

@MageMasher
Forked from bmaddy/deps.edn
Created December 26, 2018 20:54
Show Gist options
  • Save MageMasher/ab4a99842a7a507c49a68aac2466032e to your computer and use it in GitHub Desktop.
Save MageMasher/ab4a99842a7a507c49a68aac2466032e to your computer and use it in GitHub Desktop.
Playing around with caching
{:deps
{org.clojure/clojure {:mvn/version "1.10.0-RC5"}
#_#_org.clojure/spec.alpha {:mvn/version "0.2.176"}
#_#_org.clojure/test.check {:mvn/version "0.10.0-alpha3"}
org.clojure/core.cache {:mvn/version "0.7.1"}
org.clojure/core.memoize {:mvn/version "0.7.1"}
}}
(ns multi-key-cache
(:require [clojure.core.cache :as ccache]
[clojure.core.memoize :as memo]))
;; Need a cache that takes a function for missing. that fn takes the missed keys and returns their values in order.
;; (assoc cache [:a :b] [1 2])
(deftype MultiKeyCache [cache fetch-fn]
ccache/CacheProtocol
(lookup [_ items]
(mapv cache items))
(lookup [_ items not-founds]
(mapv cache items not-founds))
(has? [_ items]
(every? #(contains? cache %) items))
(hit [this items]
this)
(miss [_ items _]
(println "miss " items)
(let [to-fetch (remove (set (keys cache)) items)
results (fetch-fn to-fetch)]
(assert (map? results) "fetch-fn must return a map of keys to their new values.")
(assert (= to-fetch (keys results)))
(MultiKeyCache. (merge cache results) fetch-fn)))
(evict [_ keys]
(MultiKeyCache. (apply dissoc cache keys) fetch-fn))
(seed [_ base]
(MultiKeyCache. base fetch-fn))
Object
(toString [_] (str cache)))
(comment
(def C (MultiKeyCache. {} (fn [items]
(println "Fetching items " items)
(zipmap items (range)))))
(def C' (if (cache/has? C [:a])
(cache/hit C [:a])
(cache/miss C [:a] nil)))
(cache/has? C' [:a])
(cache/lookup C' [:a])
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment