From 2fd394b6c1f845c74ed69f05807c4cb248c9b8b4 Mon Sep 17 00:00:00 2001 From: Jeremy Penner Date: Tue, 19 Mar 2013 21:46:43 -0400 Subject: [PATCH] Implement a "nearest time" function for timelines --- src/hottub/timeline.clj | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/hottub/timeline.clj b/src/hottub/timeline.clj index d0447aa..dc09ec6 100644 --- a/src/hottub/timeline.clj +++ b/src/hottub/timeline.clj @@ -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))))))