I have a map m
, a key k
and a function f
. Is it possible to rewrite this code simpler?
(assoc m k (f (get m k))
set() overwrites the value if the key already exists in the map. How can I test this easily when in a big project? Are there any website you can use for javascript coding? what should happen instead?
map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
The returning value The first difference between map() and forEach() is the returning value. The forEach() method returns undefined and map() returns a new array with the transformed elements. Even if they do the same job, the returning value remains different.
Try clojure.core/update-in
(update-in m [k] f)
Edit: Clojure 1.7 introduced clojure.core/update
(update m k f)
update-in does this nicely, though it's especially useful for nested maps:
> (update-in {:a 4} [:a] + 7)
{:a 11}
> (update-in {:a {:b 4 :c {:d 8}} :q :foo} [:a :c :d] + 7)
{:a {:c {:d 15}, :b 4}, :q :foo}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With