javascript2016
javascript2016

Reputation: 1013

How to write a recursive reduce function?

I am trying to write a reduce function using recursion. I am learning recursion and its part of an exercise so Im trying to understand what is it that doesn't work in my code. Happy about any help! Ps. its suppose to start from the end of the array (so for example yeh becomes hey)

var strings = function(previous,current) {
    return previous+current;
};

function reducing(arr,start,func) {

    if (arr.length == 0) {
        return start;
    }
    else if (arr.length == 1) {
        return arr[0];
    }
    else {
        return func(start,arr[arr.length-1]) + reducing(arr.slice(1),start,func);
    }
}

reducing(['y','e','h'],'',strings)

Upvotes: 0

Views: 2195

Answers (2)

Carlos Rufo
Carlos Rufo

Reputation: 446

Another solution:

const reduce = (arr, fn, initial) =>
  (reduceAux = (index, value) =>
    index > arr.length-1
      ? value
      : reduceAux(index+1, fn(value, arr[index], index, value))
  )(0, initial);

Upvotes: 0

Dhananjaya Kuppu
Dhananjaya Kuppu

Reputation: 1322

This could be the problem, instead of reducing(arr.slice(1),start,func) try reducing(arr.slice(0, arr.length-1),start,func) as below:

function reducing(arr,start,func) {
  if (arr.length == 0) {
     return start;
  }
  else if (arr.length == 1) {
     return arr[0];
  }
  else {
    return func(start, arr[arr.length-1]) + reducing(arr.slice(0, arr.length -1),start,func);
 }
}

Upvotes: 2

Related Questions