Apply a sequence of functions to data

123 Views Asked by At

I wish apply a sequence of functions to a data, like pipe: http://ramdajs.com/0.14/docs/#pipe

I know it has ->>and ->, also I have difficulty in defining the internal functions

(defn create
  ([code error] {:statusCode code :error error})
  ([code error & [message data]]
   (create code error) - I want pipe it result
                       to a function that check if 
                       message if defined then merge with
                       {:message message}, then
                       apply to a function that checks if data
                       is defined an merge with it
))
1

There are 1 best solutions below

0
On BEST ANSWER

You could use cond-> threading macro to merge only defined variables:

(defn create
  ([code error]
    {:statusCode code :error error})
  ([code error & [message data]]
    (cond-> (create code error)
      message (assoc :message message)
      data    (assoc :data    data   ))))

or you could define small assoc-if-defined helper and use ordinary -> threading macro:

(defn- assoc-if-defined
  [m k v]
  (if (nil? v) m (assoc m k v)))

(defn create
  ([code error]
    {:statusCode code :error error})
  ([code error & [message data]]
    (-> (create code error)
        (assoc-if-defined :message message)
        (assoc-if-defined :data    data   ))))