for ex: I have this array
arr=[1,3,7,8];
1st call will result in: [4,8,9]
2nd Call will result in:[12,13]
3rd call will result in:[25]
How to do this using recursion in javascript?
You have 3 cases to consider
const foo = ([x,...xs]) => {
if (x === undefined)
return []
else if (xs.length === 0)
return [x]
else
return foo(xs.map(y => x + y))
}
console.log(foo([])) // []
console.log(foo([1])) // [1]
console.log(foo([1,3])) // [4]
console.log(foo([1,3,7])) // [12]
console.log(foo([1,3,7,8])) // [25]
The function could be improved if you separate some of the concerns by writing some helpers
const add = x => y => x + y
const isEmpty = xs => xs.length === 0
const isNull = x => x == null
const foo = ([x,...xs]) => {
if (isNull(x))
return []
else if (isEmpty(xs))
return [x]
else
return foo(xs.map(add(x)))
}
console.log(foo([])) // []
console.log(foo([1])) // [1]
console.log(foo([1,3])) // [4]
console.log(foo([1,3,7])) // [12]
console.log(foo([1,3,7,8])) // [25]
sum = ([h,...t]) => h && sum(t.map(a => a + h)) || h?