Skip to main content

Refactor accumulate with Functional Programming / closure

old way:

function accumulate(arr) {
let result = []
let sum = 10

for (let i = 0; i < arr.length; i++) {
sum += arr[i]
result.push(sum)
}
return result
}


in functional programming

  1. no mutation - don't mutate data
  2. pure function - no side effects
  3. 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 ]