16
I have an array of items like so:
@items = [
{price: 12, quantity:1},
{price: 4, quantity:1},
{price: 8, quantity:1}
]
And I am looking for something like this:
sumPrice: ->
@items.sum (item) -> item.price * item.quantity
Or anything as close as possible to this, that makes it super-easy for everyone reading the code to understand whats happening.
So far I came up with:
sumPrice: ->
(items.map (a) -> a.price * a.quantity).reduce (a, b) -> a + b
- contains too much functional magic
- loses descriptiveness
And:
sumPrice: ->
sum = 0
for item in items
sum += item.price * item.quantity
sum
- which can be understood by novice JS/Coffee programmers
- feels a bit stupid
I love CoffeeScript so I hope there is a nicer solution to this & similar scenarios that I miss.