Skip to content

Instantly share code, notes, and snippets.

@WhittlesJr
Last active November 26, 2018 15:33
Show Gist options
  • Save WhittlesJr/6829d040053078153059ae6733d30608 to your computer and use it in GitHub Desktop.
Save WhittlesJr/6829d040053078153059ae6733d30608 to your computer and use it in GitHub Desktop.
(defn reduce-kvs [rf init kvs]
(reduce (fn [acc [k v]] (rf acc k v)) init (partition-all 2 kvs)))
(defn assoc-if
"Assoc each kv if (pred value) is true
(assoc-if odd? {:a 1} :b 2 :c 3)
=> {:a 1 :c 3}"
([pred m k v ] (if (pred v) (assoc m k v) (or m {})))
([pred m k v & kvs]
(reduce-kvs
(fn [m k v] (assoc-if pred m k v))
(assoc-if pred m k v)
kvs))
([pred m kvs]
(apply (partial assoc-if pred m) kvs)))
(defn assoc-over-nil
"Assoc each kv if the value in the original map is nil or nonexistant
(assoc-over-nil {:a 1} :b 2)
=> {:a 1 :b 2}
(assoc-over-nil {:a 1 :b nil} :a 2 :b 2)
=> {:a 1 :b 2}"
{:added "3.0"}
([m k v ] (if (some? (get m k)) (or m {}) (assoc m k v)))
([m k v & kvs]
(reduce-kvs
(fn [m k v] (assoc-over-nil m k v))
(assoc-over-nil m k v)
kvs))
([m kvs]
(apply (partial assoc-over-nil m) kvs)))
(defn assoc-new
"Assoc each kv if the original map does not contain the key
(assoc-new {:a 1} :b 2)
=> {:a 1 :b 2}
(assoc-new {:a 1 :b nil} :a 2 :b 2 :c 3)
=> {:a 1 :b nil :c 3}"
([m k v ] (if (contains? m k) (or m {}) (assoc m k v)))
([m k v & kvs]
(reduce-kvs
(fn [m k v] (assoc-new m k v))
(assoc-new m k v)
kvs))
([m kvs]
(apply (partial assoc-new m) kvs)))
(def assoc-some
"Assoc each kv if its value is not nil.
(assoc-some {:a 1} :b 2 :c nil)
=> {:a 1 :b 2}"
(partial assoc-if some?))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment