Closed dmcgillen closed 1 year ago
Good catch! It's a bit pedantic, but maybe it's best only to make acc persistent if it's not empty:
(defn assoc-some
"Associates a key k, with a value v in a map m, if and only if v is not nil."
([m k v]
(if (nil? v) m (assoc m k v)))
([m k v & kvs]
(loop [acc (assoc-some-transient! (transient (or m {})) k v)
kvs kvs]
(cond
(next kvs) (recur (assoc-some-transient! acc (first kvs) (second kvs))
(nnext kvs))
(zero? (count acc)) m ; see CLJ-1872
:else (persistent! acc)))))
That looks a lot tidier to me
I only know this because I've been through the PR process here before, but I expect you'll be asked to keep your line widths ≤80 chars (that's why I put (nnext kvs))
on a newline).
Thanks @tomdl89. I think I spent more time thinking about the formatting when I was looking at this earlier than the change itself! I've gone with what you've put above.
Thanks! Can you change the commit message to:
Make assoc-some for nil map consistent with assoc
Fixes #73.
That will put the subject line of the commit message under 50 characters (see CONTRIBUTING.md), and link the commit back to the issue it solves.
Done
Fixes https://github.com/weavejester/medley/issues/73
This makes the behaviour as it was in 1.5.0, which is more consistent with Clojure core fns.
(medley/assoc-some nil :a 1)
{:a 1}
{:a 1}
(medley/assoc-some nil :a 1 :b 2)
java.lang.NullPointerException
{:a 1 :b 2}
(medley/assoc-some nil :a nil)
nil
nil
(medley/assoc-some nil :a nil :b nil)
java.lang.NullPointerException
nil
I think
nil
should be returned for a nil input when nothing isassoc
ed. This seems consistent with things such as:I ran it through some benchmarks given the recent changes were to improve performance to ensure it wasn't impacted. There is essentially no difference when running the benchmark provided in https://github.com/weavejester/medley/pull/68 (which you'd expect given it spends most of its time in the loop and the only change is an extra step at each of the beginning and the end):
1.6.0:
This PR:
A more realistic test I suppose is a more minimal assoc so that the change has more impact:
1.6.0:
This PR: