user6324692
user6324692

Reputation:

Processing multiple fields with map in Luminus/Compojure

I have this:

(defn my-page []
  (layout/render
   "page1.html" ({:articles (map
                             #(update % :field1 (fn [d] (something.... )))
                              (db/get-all-articles))})))
                            ; how can I call map again to process other fields?
                            ; (map for :field2 .... ???? how?)
                            ; (map for :field3 .... ???? how?)     

I want to preprocess other fields also. How can I properly do that? I mean, since I already have the variable :article and function map, how would I do map again for other fields such as :field2 and field3?

Upvotes: 1

Views: 40

Answers (2)

leetwinski
leetwinski

Reputation: 17859

you could also generalize these updates with reduction:

user> (def items {:field1 1
                  :field2 2
                  :field3 3})
#'user/items
user> (reduce-kv update items {:field1 inc
                               :field2 dec
                               :field3 #(* % 2)})
{:field1 2, :field2 1, :field3 6}

Upvotes: 0

Piotrek Bzdyl
Piotrek Bzdyl

Reputation: 13175

Use a threading macro:

(def m {:field1 1
        :field2 2
        :field3 3})

(-> m
  (update :field1 (fn [v1] ...))
  (update :field2 (fn [v2] ...))
  (update :field3 (fn [v3] ...)))

It's equivalent to:

(update
  (update 
    (update m :field1 (fn [v1] ...))
    (fn [v2] ...))
  (fn [v3] ...))

You can enclose such logic in a function and use it to map all the articles.

Upvotes: 0

Related Questions