Skip to content

Instantly share code, notes, and snippets.

@danownsthisspace
Created October 3, 2021 18:26
Show Gist options
  • Save danownsthisspace/4c231fd58f2d191dfc7732095cbd1edb to your computer and use it in GitHub Desktop.
Save danownsthisspace/4c231fd58f2d191dfc7732095cbd1edb to your computer and use it in GitHub Desktop.
Create a look up map with Clojure for faster record access
(def users [{:id 1
:email "michael.lawson@reqres.in"
:first_name "Michael"
:last_name "Lawson"
:avatar "https://reqres.in/img/faces/1-image.jpg"}
{:id 2
:email "lindsay.ferguson@reqres.in"
:first_name "Lindsay"
:last_name "Ferguson"
:avatar "https://reqres.in/img/faces/2-image.jpg"}
{:id 3
:email "tobias.funke@reqres.in"
:first_name "Tobias"
:last_name "Funke"
:avatar "https://reqres.in/img/faces/3-image.jpg"}
{:id 4
:email "byron.fields@reqres.in"
:first_name "Byron"
:last_name "Fields"
:avatar "https://reqres.in/img/faces/4-image.jpg"}
{:id 5
:email "george.edwards@reqres.in"
:first_name "George"
:last_name "Edwards"
:avatar "https://reqres.in/img/faces/5-image.jpg"}
{:id 6
:email "rachel.howell@reqres.in"
:first_name "Rachel"
:last_name "Howell"
:avatar "https://reqres.in/img/faces/6-image.jpg"}])
(first (filter #(= (:id %) 3) users))
(def reduce-lookup (reduce (fn [acc {:keys [id] :as user}]
(into acc {id user})) {} users))
(get reduce-lookup 3)
(def groupby-lookup (into {} (map (fn [[id user-list]]
{id (first user-list)}) (group-by :id users))))
(get groupby-lookup 3)
(def juxt-lookup (into {} (map (juxt :id identity) users)))
(get juxt-lookup 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment