nums = [2 5 3 7]
result = []
result.push {x:nums[0]}
for n in nums.slice(1)
result.push {n:n + result[-1].x}
log result
# [{x:2} {x:7} {x:10} {x:17}]
This is hard to express functionally using the function map
because each element depends on the previous element. What is the correct functional solution for this algorithm?
simplest way i know avoids performance-robbing closures, variables, extra function overhead, and globals:
result= [2, 5, 3, 7].map(function(a){ return { x: this[0]+=a }; }, [0]);
JS provides the seldom-used 2nd .map() parameter to store any state you need between iterations.
It probably doesn't get any simpler than this, but don't know coffee, sorry...
EDIT: whipped up a dual-language (js+cs) demo: http://pagedemos.com/maptranforms/
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