Fork me on GitHub
#rewrite-clj
<
2022-11-04
>
pavlosmelissinos18:11:57

Hello ๐Ÿ™‚ How do I mimic "clojure.core/filter" & first with rewrite-clj? Searched the docs but couldn't find the answer. Context: I have an edn file that contains a vector and I want to replace the entry that contains a specific id. I'm pretty sure I can use rewrite-clj.zip/replace as soon as I identify the correct node but I'm having trouble finding it. Example in ๐Ÿงต

pavlosmelissinos18:11:31

(def content "[{:id :a :label \"foo\"}
               {:id :b :label \"bar\"}
               {:id :c :label \"baz\"}
               {:id :d :label \"bat\"}]")
(defn replace-entry [content id new-content]
    ,,,)
(replace-entry content :c {:id :c :label "bal" :organization "me"})

=> "[{:id :a :label \"foo\"}
     {:id :b :label \"bar\"}
     {:id :c :label \"bal\" :organization \"me\"}
     {:id :d :label \"bat\"}]"

borkdude18:11:10

Not sure right away, but perhaps it might give you some inspiration

pavlosmelissinos18:11:31

Thanks, I'll take a look ๐Ÿ™‚

borkdude18:11:24

I think you could combine it at least to move to the map with the right id and then remove or replace it using a zipper operation

pavlosmelissinos22:11:08

In case anyone is interested, this is the closest I came up with...

(defn filterz [zloc f] (z/find zloc #(->> % z/string f)))

  (defn replace-entry [content id new-content]
    (-> (z/of-string content)
        z/down
        (filterz #(= (:id (clojure.edn/read-string %)) id))
        (z/replace new-content)
        z/root-string))
I think it's good enough for now ๐Ÿ˜„

๐Ÿ‘ 2
snoe16:11:02

z/sexpr may be useful to you in the future, rather than comparing strings.

๐Ÿ‘ 1
borkdude16:11:15

z/sexpr may blow up in your face sometimes though ;)

pavlosmelissinos18:11:38

I'll look it up, thanks