Skip to content

Instantly share code, notes, and snippets.

@BuddhiLW
Created May 18, 2023 18:44
Show Gist options
  • Save BuddhiLW/560cae4f409156248555df4ded486aeb to your computer and use it in GitHub Desktop.
Save BuddhiLW/560cae4f409156248555df4ded486aeb to your computer and use it in GitHub Desktop.
Group and keywordize data, with Clojure (useful for requests with ids as strings)
;; keywordize-at-keys: https://gist.github.com/vvvvalvalval/d31f8980045f3da3b3415092f6db32b6
(defn associate-by [f coll]
(into {} (map (juxt f identity) coll)))
(defn associate-by-kkeyword-value
"Associate by key the key-work values and transform key to keyword, as well as it's value.
Generally, used for grouping data by the unique values in a coll, coming from requests."
[key coll]
(->> coll
(keywordize-at-keys #{key})
(associate-by key)))
;; Example:
;; --------------------------------------------------------------------
(let [ex [{:recipe/recipe_id "a1995316-80ea-4a98-939d-7c6295e4bb46"
:recipe/public true
:recipe/prep_time 5
:recipe/name "Avocado Salad"
:recipe/img "https://res.cloudina … cipe/vegie-salad.jpg"
:recipe/favorite_count 5
:recipe/uid "jade@mailinator.com"}]]
(associate-by-kkeyword-value :recipe/recipe_id ex))
;; Result:
;; -------------------------------------------------------------------
;; => {:a1995316-80ea-4a98-939d-7c6295e4bb46
;; #:recipe{:recipe_id :a1995316-80ea-4a98-939d-7c6295e4bb46,
;; :public true,
;; :prep_time 5,
;; :name "Avocado Salad",
;; :img "https://res.cloudina … cipe/vegie-salad.jpg",
;; :favorite_count 5,
;; :uid "jade@mailinator.com"}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment