Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Last active September 11, 2022 22:47
Show Gist options
  • Save boraseoksoon/abe5afe494a5e4afdc7f5a2bbe08584e to your computer and use it in GitHub Desktop.
Save boraseoksoon/abe5afe494a5e4afdc7f5a2bbe08584e to your computer and use it in GitHub Desktop.
merge maps into a unified one map.
(defn merge-maps [& maps]
;; (sanitize-map)
(if (every? map? maps)
(apply merge-with merge-maps maps)
(last maps)))
(defn sanitize-map [m]
(if (map? m)
(let [clean-val (fn [[k v]]
(let [v' (sanitize-map v)]
(when-not (nil? v')
[k v'])))
m' (->> (map clean-val m)
(remove nil?)
(into {}))]
(when-not (empty? m') m')) m))
(def json {:k1 "k1" :k2 "k2" :k5 "k5"})
(def json2 {:k2 "k2" :k3 "k3" :k10 nil})
(def json3 {:a "a" :b "b"})
json
json2
(merge-maps json json2)
;; {:k1 "k1", :k2 "k2", :k5 "k5", :k3 "k3", :k10 nil}
(merge-maps json json2 json3)
;; {:k1 "k1", :k2 "k2", :k5 "k5", :k3 "k3", :k10 nil, :a "a", :b "b"}
(merge-maps json json2 {:test "test" :test2 "test2" :inside {:in1 "in1" :in2 "in2"}}
;; {:k1 "k1", :k2 "k2", :k5 "k5", :k3 "k3", :k10 nil, :test "test", :test2 "test2", :inside {:in1 "in1", :in2 "in2"}}
;; TODO:
;; 0. allow nil flag
;; 1. flatten nested map flag
;; 2. what else?
;; (defn merge-maps
;; [& {:keys [& maps allowNil?] :or { allowNil? true }}]
;; (defn sanitize-map [m]
;; (if (map? m)
;; (let [clean-val (fn [[k v]]
;; (let [v' (sanitize-map v)]
;; (when-not (nil? v')
;; [k v'])))
;; m' (->> (map clean-val m)
;; (remove nil?)
;; (into {}))]
;; (when-not (empty? m') m')) m))
;; (if allowNil?
;; (if (every? map? maps)
;; (apply merge-with merge-maps :maps maps :allowNil? allowNil?)
;; (last maps))
;; (sanitize-map
;; (if (every? map? maps)
;; (apply merge-with merge-maps :maps maps :allowNil? allowNil?)
;; (last maps))))))
;; (def json {:k1 "k1" :k2 "k2" :k5 "k5"})
;; (def json2 {:k2 "k2" :k3 "k3" :k10 nil})
;; json
;; json2
;; (merge-maps :maps json json2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment