Skip to content

Instantly share code, notes, and snippets.

@martinklepsch
Last active August 20, 2017 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinklepsch/bcabc82bd2da32d66a89c1235ff914cf to your computer and use it in GitHub Desktop.
Save martinklepsch/bcabc82bd2da32d66a89c1235ff914cf to your computer and use it in GitHub Desktop.
(ns date.partition
(:import (java.time Instant Duration)))
(defprotocol IInterval
(within? [this date] "xxx"))
(defrecord Interval [start end]
IInterval
(within? [this date]
(< (.toEpochMilli (:start this))
(.toEpochMilli (.toInstant date))
(.toEpochMilli (:end this)))))
(defn interval-seq
[start interval-size]
(let [i (->Interval start (.plus start interval-size))]
(cons i (lazy-seq (interval-seq (:end i) interval-size)))))
;; interval-seq usage:
;; (interval-seq (.toInstant some-date) interval)
(def dates
[(java.util.Date. 2016 8 1)
(java.util.Date. 2016 9 1)
(java.util.Date. 2016 10 1)
(java.util.Date. 2016 11 1)
(java.util.Date. 2016 12 1)
(java.util.Date. 2017 1 1)
(java.util.Date. 2017 2 1)])
(defn partition-dates [dates interval-size])
;; (partition-dates dates (Duration/ofMonths 2))
;; =>
;; [[(java.util.Date. 2016 8 1)
;; (java.util.Date. 2016 9 1)
;; (java.util.Date. 2016 10 1)]
;; [(java.util.Date. 2016 11 1)
;; (java.util.Date. 2016 12 1)]
;; [(java.util.Date. 2017 1 1)
;; (java.util.Date. 2017 2 1)]
@martinklepsch
Copy link
Author

martinklepsch commented Aug 20, 2017

Potential solution

  (def r
    (reduce (fn [{:keys [dates] :as x} interval]
              (let [[in-interval rst] (split-with #(within? interval %) dates)]
                (if (seq rst)
                  (-> x
                      (update :partitioned conj in-interval)
                      (assoc :dates rst))
                  (reduced (conj (:partitioned x) in-interval)))))
            {:dates (map :ts quotes)
             :partitioned []}
            (interval-seq (.toInstant (:ts (first (sort-by :ts quotes))))
                          (Duration/ofDays 2))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment