Fork me on GitHub
#code-reviews
<
2020-01-23
>
dharrigan21:01:39

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...

dharrigan21:01:46

(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)

dharrigan21:01:45

(fields could be empty btw, that's why the seq is there)

seancorfield21:01:20

When does fields change its value, relative to the map/`select-keys` code?

dharrigan21:01:49

it's passed in on the query, i.e., /api/coll?fields=a,b so it's dynamic

dharrigan21:01:04

could be 0...N fields

dharrigan21:01:51

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

seancorfield21:01:20

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.

dharrigan21:01:46

kk, I sorta thought I was over thinking it 🙂 But always looking to see if I can improve things 🙂

dharrigan21:01:25

Thanks Sean! 🙂

noisesmith21:01:42

btw select-keys does work on string keys, so in some contexts you can simplify by not keywordizing user input

seancorfield21:01:38

as long as coll also has string keys, right?

noisesmith21:01:38

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

seancorfield21:01:18

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 🙂

dharrigan21:01:59

trying that out in my unit test

dharrigan21:01:50

well, I'll be a simian's close male relative!

dharrigan21:01:11

Clojure amazes me continously - in good ways! 🙂