Skip to content

Commit 5dcc20a

Browse files
committed
backport compojure.api.common
1 parent e683557 commit 5dcc20a

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

src/compojure/api/common.clj

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
(ns compojure.api.common)
1+
(ns compojure.api.common
2+
(:require [linked.core :as linked]))
23

34
(defn plain-map?
45
"checks whether input is a map, but not a record"
@@ -41,3 +42,39 @@
4142
(if (get v 1)
4243
(apply merge v)
4344
(get v 0)))
45+
46+
(defn fast-map-merge
47+
[x y]
48+
(reduce-kv
49+
(fn [m k v]
50+
(assoc m k v))
51+
x
52+
y))
53+
54+
(defn fifo-memoize [f size]
55+
"Returns a memoized version of a referentially transparent f. The
56+
memoized version of the function keeps a cache of the mapping from arguments
57+
to results and, when calls with the same arguments are repeated often, has
58+
higher performance at the expense of higher memory use. FIFO with size entries."
59+
(let [cache (atom (linked/map))]
60+
(fn [& xs]
61+
(or (@cache xs)
62+
(let [value (apply f xs)]
63+
(swap! cache (fn [mem]
64+
(let [mem (assoc mem xs value)]
65+
(if (>= (count mem) size)
66+
(dissoc mem (-> mem first first))
67+
mem))))
68+
value)))))
69+
70+
;; NB: when-ns eats all exceptions inside the body, including those about
71+
;; unresolvable symbols. Keep this in mind when debugging the definitions below.
72+
73+
(defmacro when-ns [ns & body]
74+
`(try
75+
(eval
76+
'(do
77+
(require ~ns)
78+
~@body))
79+
(catch Exception ~'_)))
80+

0 commit comments

Comments
 (0)