Ep 016: When 8 - 1 = 6

Play Episode

Christoph discovers that time creates its own alternate universe.

Related episodes:

Clojure in this episode:

Related projects:

Code sample from this episode:

(ns app.time
  (:require
    [clojure.java.io :as io]
    [java-time :as jt]))

(def timestamp-re #"(\w+\s\w+\s\d+\s\d+)\s+(\d{2}:\d{2})-(\d{2}:\d{2})")

(defn localize [dt tm]
  (jt/zoned-date-time dt tm (jt/zone-id "America/Los_Angeles")))

(defn parse-time [time-str]
  (jt/local-time "HH:mm" time-str))

(defn parse-date [date-str]
  (jt/local-date "EEE MMM dd yyyy" date-str))

(defn parse-for-minutes
  [line]
  (if-let [[whole dt start end] (re-matches timestamp-re line)]
    (let [date (parse-date dt)
          start (localize date (parse-time start))
          end (localize date (parse-time end))]
      (if (jt/before? start end)
        (jt/time-between start end :minutes)
        (jt/time-between start (jt/plus end (jt/days 1)) :minutes)))
    0))

(defn total-time
  [filename]
  (with-open [rdr (io/reader filename)]
    (loop [total 0
           lines (line-seq rdr)]
      (if lines
        (recur (+ total (or (some-> (first lines) parse-for-minutes) 0)) (next lines))
        total))))