Files
integreat/src/cljc/auto_ap/utils.cljc

108 lines
2.6 KiB
Clojure

(ns auto-ap.utils
#?@
(:clj
[(:require [com.unbounce.dogstatsd.core :as statsd]
[clojure.tools.logging :as log]
[unilog.context :as lc])]))
(defn by
([f xs]
(by f identity xs))
([f fv xs]
(reduce
#(assoc %1 (f %2) (fv %2))
{}
xs)))
(defn replace-if [f candidate existing]
(reduce
(fn [xs x]
(if (f x candidate)
(conj xs candidate)
(conj xs x)))
[]
existing))
(defn replace-by [xs f x]
(let [found? (atom false)
replaced (mapv
(fn [t]
(if (= (f t) (f x))
(do (reset! found? true)
x)
t))
xs)]
(if @found?
replaced
(into [x] replaced))))
(defn remove-by [xs f x]
(into []
(filter
(fn [t]
(if (= (f t) (f x))
false
true))
xs)))
(defn merge-by [xs f x]
(let [found? (atom false)
replaced (mapv
(fn [t]
(if (= (f t) (f x))
(do (reset! found? true)
(merge t x))
t))
xs)]
(if @found?
replaced
(into [x] replaced))))
(defn dollars-0? [amt]
(< -0.001 amt 0.001))
(defn dollars= [amt1 amt2]
(dollars-0? (- amt1 amt2) ))
(defn deep-merge [v & vs]
(letfn [(rec-merge [v1 v2]
(if (and (map? v1) (map? v2))
(merge-with deep-merge v1 v2)
v2))]
(if (some identity vs)
(reduce #(rec-merge %1 %2) v vs)
(last vs))))
(def default-pagination-size 20)
(defn allow-once [f]
(let [in-progress? (atom false)]
(fn []
(when (= false @in-progress?)
(try
(reset! in-progress? true)
(f)
(finally
(reset! in-progress? false)))))))
(defn heartbeat [f id]
(fn []
#?(:clj (do
(lc/with-context {:source id}
(try
(log/info "Starting background process " id)
(f)
(log/info "Completed background process " id)
(statsd/service-check {:name (str id)
:status :ok}
nil)
(catch Exception e
(log/error e)
(statsd/service-check {:name (str id)
:status :critical}
nil)))))
:cljs (do (println "Heartbeat for " id)
(f)))))