Skip to content

Instantly share code, notes, and snippets.

@plexus
Created March 12, 2021 12:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plexus/42c0cbc97455a1656471e5d31c67f122 to your computer and use it in GitHub Desktop.
Save plexus/42c0cbc97455a1656471e5d31c67f122 to your computer and use it in GitHub Desktop.
Doing key lookup in Clojure
;; If it's a record-like thing then we want to emphasize
;; that it's a key-lookup, so use (:key coll)
(:uri req)
(:email member)
;; Some collections behave more like functions, here use (coll key),
;; that way someone reading the code without context can understand it,
;; without having to know that it's really a map or set
(def allowed-role? #{:admin :mod})
(allowed-role? (:role user))
(def message-color {:error "red" :warning "orange" :success "green"})
(let [{:keys [content type]} message]
[:p {:style {:background-color (message-color type)}}
content])
;; This also makes it clear that you can use functional composition
(def has-access? (comp allowed-role? :role))
(has-access? user)
;; If both collection and key are variables, then (get coll key)
;; can help keep things readable, because it's explicit about
;; the roles of its arguments
(def flags {:f "-format" :d "-duration"})
(defn cli-args [opts]
(for [[k v] opts]
(str (get flags k) " " v)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment