Created
October 3, 2021 18:26
-
-
Save danownsthisspace/4c231fd58f2d191dfc7732095cbd1edb to your computer and use it in GitHub Desktop.
Create a look up map with Clojure for faster record access
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(def users [{:id 1 | |
:email "[email protected]" | |
:first_name "Michael" | |
:last_name "Lawson" | |
:avatar "https://reqres.in/img/faces/1-image.jpg"} | |
{:id 2 | |
:email "[email protected]" | |
:first_name "Lindsay" | |
:last_name "Ferguson" | |
:avatar "https://reqres.in/img/faces/2-image.jpg"} | |
{:id 3 | |
:email "[email protected]" | |
:first_name "Tobias" | |
:last_name "Funke" | |
:avatar "https://reqres.in/img/faces/3-image.jpg"} | |
{:id 4 | |
:email "[email protected]" | |
:first_name "Byron" | |
:last_name "Fields" | |
:avatar "https://reqres.in/img/faces/4-image.jpg"} | |
{:id 5 | |
:email "[email protected]" | |
:first_name "George" | |
:last_name "Edwards" | |
:avatar "https://reqres.in/img/faces/5-image.jpg"} | |
{:id 6 | |
:email "[email protected]" | |
: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