I have a function that returns a map. The keys are static, but the values are conditional. Like this:
(defn map-returning-function [x y]
{:a (if (some-test-fn x) "one value" "other value"
:b (if (some-test-fn x) 15 25
:c (if (different-test y) :one :two})
Is there some more elegant way to achieve this without needing to write the if test for each value? The only other way I can think of is
(defn another-map-returning-function [x y]
(if (some-test-fn x)
{:a "one value", :b 15, :c (if (different-test y) :one :two)}
{:a "other value" :b 25, :c (if (different-test y) :one :two)}))
which doesn’t seem much better to me since it repeats the key names for each branch of the conditional and it repeats of the function call on different-test. And heaven forbid that I need a cond instead of just an if.
How about this:
Conditions executed once and in one place, then used in another. Depends on context and personal preference though. Something more like your example may be cleaner: