code-reviews

dharrigan 2020-01-23T21:02:39.001500Z

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

dharrigan 2020-01-23T21:02:46.001700Z

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

dharrigan 2020-01-23T21:03:45.002200Z

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

seancorfield 2020-01-23T21:18:20.002700Z

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

dharrigan 2020-01-23T21:18:49.003300Z

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

dharrigan 2020-01-23T21:19:04.003700Z

could be 0...N fields

dharrigan 2020-01-23T21:19:51.004500Z

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

seancorfield 2020-01-23T21:20:20.005200Z

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.

dharrigan 2020-01-23T21:20:46.005700Z

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

dharrigan 2020-01-23T21:21:25.005900Z

Thanks Sean! 🙂

2020-01-23T21:22:42.006700Z

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

seancorfield 2020-01-23T21:23:38.007100Z

as long as coll also has string keys, right?

2020-01-23T21:24:38.008200Z

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

seancorfield 2020-01-23T21:25:18.009100Z

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 🙂

2020-01-23T21:26:01.009700Z

right

dharrigan 2020-01-23T21:28:46.009900Z

oooh

dharrigan 2020-01-23T21:28:59.010100Z

trying that out in my unit test

dharrigan 2020-01-23T21:31:50.010500Z

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

dharrigan 2020-01-23T21:32:11.010800Z

Clojure amazes me continously - in good ways! 🙂