Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a functional-style replacement for this loop?

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?

like image 320
MaiaVictor Avatar asked Nov 27 '22 03:11

MaiaVictor


1 Answers

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/

like image 162
dandavis Avatar answered Dec 07 '22 00:12

dandavis