简体   繁体   中英

ClojureScript - store functions in map

I am using a map to store function calls (in ClojureScript, but it should be the same in Clojure) :

(def parse-fn {:json    js/JSON.parse
               :edn     read-string
               :transit t->clj})

I then have a transform function like the following :

(defn transform [format data]
  ((get parse-fn format) data))

Calling transform like that : (transform :transit data) works nicely. I am only worried about the readability of the transform function. It is not immediately obvious that the first thing is a function.

Edit : I cannot just call (:transit parse-fn) since the format comes from another function, as in : (another-fn [... format ...] ... (transform format data))

Is there an explicit call function, or is the structure of this code not idiomatic ?

Maybe consider treating the keyword as the function.

((:transit parse-fn) data)

To me the more terse approach helps me recognise the first element as distinct.

Alternatively, you can treat the map as the function instead.

((parse-fn :transit) data)

As I understand, the first approach is generally considered more idiomatic and it can also be optimized more intelligently .

Your initial design is completely readable. Passing functions to other functions that do the actual work is a fairly normal way of doing things. I don't think you need to change anything to "make it more readable". If i was going to change anything to make i more clrearly spelled out would be to change the name of transform to transform-lookup or get-transform

(another-fn [... format ...] ... (transform-lookup format data))

or

(another-fn [... format ...] ... (get-transform format data))

Though this is a very minor distinction and it's fine the way it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM