Search code examples
clojure

unable to sort a map containing date-time


I am trying to sort a map based on its date-time value. The code below uses the function from clj-time -

(def items {:a {:time (date-time 2013 12)} :b {:time (date-time 2013 11)}})

(sort-by #(-> % items :month) before? items)

IllegalArgumentException No implementation of method: :before? of protocol: #'clj-time.core/DateTimeProtocol found for class: nil clojure.core/-cache-protocol-fn (core_deftype.clj:527)

However I get the above exception. What am I doing wrong ?


Solution

  • You need to do this:

    (sort-by (fn [[k v]] (-> v :time)) before? items)
    

    In case you want a sorted-map then you need to make the date-time map as the key and :a :b as values cause sorted-map sort on key value:

    (->>  (into [] items)
          (map (fn [[k v]] [v k]))
          (flatten)
          (apply sorted-map-by #(before? (%1 :time) (%2 :time))))