Would there be a way to make this more efficient, i.e., not store fields-as-keywords
(although, I would perfer to do that work once, and not have to do it every time I map over the coll) I'm sorta thinking transducer here (since it's transforming and reducing down the collection), but not sure how I might go about that (as the first stage would be to map the fields to keywords, then apply each to select-keys on the coll...
(def fields ["a" "b"])
(def coll [:a "foo" :b "bar" :c {:d "baz"}])
(if-let [fields-as-keywords (seq (map keyword fields))]
(map #(select-keys % fields-as-keywords) coll)
coll)
(fields could be empty btw, that's why the seq
is there)
When does fields
change its value, relative to the map
/`select-keys` code?
it's passed in on the query, i.e., /api/coll?fields=a,b
so it's dynamic
could be 0...N fields
So, one of the last things I do, before handing the coll back to the API request is to only keep fields that the callee wants
You could cache that part I suppose. But, frankly, (map keyword fields)
is going to take a fairly trivial amount of time compared to everything else your API would be doing.
kk, I sorta thought I was over thinking it 🙂 But always looking to see if I can improve things 🙂
Thanks Sean! 🙂
btw select-keys
does work on string keys, so in some contexts you can simplify by not keywordizing user input
as long as coll
also has string keys, right?
as long as each map in coll has matching keys, right - it's a question of what keys make sense over the scope of the app
user=> (select-keys {:a 1 "a" 2 'a 3} [:a])
{:a 1}
user=> (select-keys {:a 1 "a" 2 'a 3} ["a"])
{"a" 2}
user=> (select-keys {:a 1 "a" 2 'a 3} ['a])
{a 3}
user=>
Just to be clear that the keys in coll
are treated distinctly as keywords, strings, and symbols 🙂right
oooh
trying that out in my unit test
well, I'll be a simian's close male relative!
Clojure amazes me continously - in good ways! 🙂