Implement a "nearest time" function for timelines

This commit is contained in:
Jeremy Penner 2013-03-19 21:46:43 -04:00
parent 1b8cb4c148
commit 2fd394b6c1

View file

@ -20,3 +20,22 @@
(defn timeline-last-value [tln]
(last (second (last tln))))
(defn- distance [tln a b]
(let [d (.compare (.comp tln) a b)]
(if (neg? d) (- d) d)))
(defn time-nearest [tln clock]
(let [akv (first (rsubseq tln <= clock))
bkv (first (subseq tln >= clock))]
(if-not akv
(if-not bkv
nil
(key bkv))
(if-not bkv
(key akv)
(let [a (key akv)
b (key bkv)
da (distance tln clock a)
db (distance tln clock b)]
(if (<= da db) a b))))))