Clojure deep-merge to ignore nil values

I am trying to deeply merge multiple cards in Clojure. I found many solutions online, most of which look something like this:

(defn deep-merge
  [& xs]
 (if (every? map? xs)
   (apply merge-with deep-merge xs)
  (last xs)))

      

The problem with this solution is that if one of the maps is nil, it will remove all previous maps (so if the last map is nil, the whole function will return nil). This is not the case with the normal merge function, which ignores nil values. Is there another simple deep merge implementation that ignores nil values?

+3


source to share


2 answers


I found this at: https://github.com/circleci/frontend/blob/04701bd314731b6e2a75c40085d13471b696c939/src-cljs/frontend/utils.cljs . He does exactly what he should.

(defn deep-merge* [& maps]
  (let [f (fn [old new]
             (if (and (map? old) (map? new))
                 (merge-with deep-merge* old new)
                 new))]
    (if (every? map? maps)
      (apply merge-with f maps)
     (last maps))))

(defn deep-merge [& maps]
  (let [maps (filter identity maps)]
    (assert (every? map? maps))
   (apply merge-with deep-merge* maps)))

      



Thank you CircleCi people!

+5


source


Delete nil

immediately?



(defn deep-merge [& xs]
  (let [xs (remove nil? xs)]
    (if (every? map? xs)
      (apply merge-with deep-merge xs)
      (last xs))))

      

+2


source







All Articles