Skip to main content

Posts

Showing posts with the label functional programming

Refactor accumulate with Functional Programming / closure

old way: function accumulate ( arr ) { let result = [] let sum = 1 0 for ( let i = 0 ; i < arr . length ; i ++) { sum += arr [ i ] result . push ( sum ) } return result } in functional programming no mutation - don't mutate data pure function - no side effects const  so we need to use filter, map, concat, reduce,  closure:  a closure is a function that references variables in the outer scope from its inner scope. function accumulate ( arr ) { let total = 10 return (() => arr . map (( num ) => { total += num return total }) ) } console . log ( sum ([ 1 , 2 , 3 ])()) => [ 11, 13, 16 ]