Skip to content

Instantly share code, notes, and snippets.

@tangrammer
Created July 19, 2018 12:55
Show Gist options
  • Save tangrammer/a8bd9dc91270ea418f107d1f9af372a6 to your computer and use it in GitHub Desktop.
Save tangrammer/a8bd9dc91270ea418f107d1f9af372a6 to your computer and use it in GitHub Desktop.
clojure implementation of formatting copyright years

clj challenge :)

(defn- parse
  "Parse years collection into years integer collection. Example: from ['1978' '1956' ...] to (1978 1956)"
  [col*]
  (map  #(Integer/parseInt %) col*))

(defn- group-consecutive-years
  "Example: from (2014 2010 2011 2012 2015 2016 2017) to ((2010 2011 2012) (2014 2015 2016 2017))"
  [years-col]
  (let [years-sorted-set (apply sorted-set years-col)
        optional-years (range (first years-sorted-set) (inc (last years-sorted-set)))]  
    (->> optional-years
         (reduce (fn [c year]
                   (if (contains? years-sorted-set year)
                     (conj c year)
                     (conj c 0))) [])
         (partition-by pos?)
         (remove (comp zero? first)))))

(defn- str-format
  "example: from ((2010 2011 2012) (2014 2015 2016 2017)) to \"2010-2012,2014-2017\""
  [years-group-col]
  (->> years-group-col
       (map (comp distinct (juxt first last)))
       (map (fn [[f l]] (if l (str f "-" l) f)))
       (interpose ",")
       (flatten)
       (apply str)))

(defn extract-copy-years
  "Example: from [\"2014\" \"2010\" \"2011\" \"2012\"  \"2015\" \"2016\" \"2017\"] to \"2010-2012,2014-2017\""
  [string-years-col]
  (-> string-years-col
      parse
      group-consecutive-years
      str-format))

;; testing example data
;; note some cols are unordered
(doseq [[v r] {["2014" "2010" "2011" "2012"  "2015" "2016" "2017"]       "2010-2012,2014-2017"
               ["2011" "2012" "2014" "2018"]                             "2011-2012,2014,2018"
               ["2011" "2012" "2013" "2014" "2015" "2016" "2017" "2018"] "2011-2018"}]
  (assert (= (extract-copy-years v) r)))


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