Fork me on GitHub
#meander
<
2023-02-17
>
noprompt18:02:14

@nyor.tr

(def data
  {:editions [{:book {:id 0
                      :title "title1"
                      :authors ["author1" "author2"]
                      :pages 123
                      :isbn "2353-2343"
                      :publication-year 1995
                      :first-edition true}}
              {:book {:id 1
                      :title "title2"
                      :authors ["author3"]
                      :pages 123
                      :isbn "6745-4623"
                      :publication-year 2001}}
              {:book {:id 2
                      :title "title1"
                      :authors ["author3"]
                      :pages 123
                      :isbn "6745-4623"
                      :publication-year 2001}}
              {:book {:id 3
                      :title "title2"
                      :authors ["author4"]
                      :pages 123
                      :isbn "6745-4623"
                      :publication-year 2001}}
              {:book {:id 4
                      :title "title1"
                      :authors ["author3"]
                      :pages 123
                      :isbn "6745-4623"
                      :publication-year 2001}}]})


(defn join-books [editions]
  (m/find editions
    (m/with [%book {:book {:title ?title
                           :authors [!authors ...]
                           & !book-data}}]
      [%book & [(m/or %book !not-book) ...]])
    (cons {:title ?title
           :authors !authors
           :book-data !book-data}
          (join-books !not-book))))

(join-books (:editions data))
;; =>
({:title "title1",
  :authors ["author1" "author2" "author3" "author3"],
  :book-data
  [{:id 0,
    :pages 123,
    :isbn "2353-2343",
    :publication-year 1995,
    :first-edition true}
   {:id 2, :pages 123, :isbn "6745-4623", :publication-year 2001}
   {:id 4, :pages 123, :isbn "6745-4623", :publication-year 2001}]}
 {:title "title2",
  :authors ["author3" "author4"],
  :book-data
  [{:id 1, :pages 123, :isbn "6745-4623", :publication-year 2001}
   {:id 3, :pages 123, :isbn "6745-4623", :publication-year 2001}]})

noprompt18:02:07

join-books can also be written with m/rewrite but m/find is best starting out.

(defn join-books [editions]
  (m/rewrite editions
    (m/with [%book {:book {:title ?title
                           :authors [!authors ...]
                           & !book-data}}]
      [%book & [(m/or %book !not-book) ...]])
    [{:title ?title
      :authors [!authors ...]
      :book-data [!book-data ...]}
     & (m/cata [!not-book ...])]

    _else []))