Ramda does have a mean
function (as well as a median
one.) So that will make your solutions fairly simple:
const calculateAveragePrice = compose (mean, pluck( 'cost'))
const products = [{cost: 300}, {cost: 700}]
console .log (
calculateAveragePrice(products)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
<script>const {compose, mean, pluck} = R </script>
Or of course you could write pipe (pluck('cost'), mean)
instead. I prefer compose
for one-liners, and pipe
for anything else, but that's just a matter of taste.
But if you didn't know that Ramda supplied this, you could write your own point-free average
function with converge
:
const average = converge(divide, [sum, length])
converge
and its cousin useWith
are designed to make it easier to write point-free versions of code. I always include a warning that point-free should rarely be a goal on its own, however. It's useful only when it serves to improve the readability of the code. Both converge
and useWith
tend to be questionable on that score. There is an alternative that is more standard in the FP world: the function lift
:
const average = lift (divide) (sum, length)
lift
transforms a function that accepts values of certain types to one that accepts containers of values of those values. And since a function that returns a value of a given type can be considered a container (squint hard if necessary), lift (f) (g, h)
is something equivalent to (x) => f (g (x), h (x))
. (There's more information in the SO question, Can't wrap my head around “lift” in Ramda.js.)
converge
is slightly more flexible, but I always use lift
if I can. It feels more standard.