Question


I'm quite new to JavaScript and don't understand a few of its behaviours. I want to write a recursive version of reduce function found in Eloquent JavaScript book. That's my code:

function rec_reduce( fn, base, list ) {
    if( list.length === 0 ) {
        return base;
    }
    else {
        rec_reduce( fn, fn( base, list[ 0 ] ), list.slice( 1 ) );
    }
}
print( rec_reduce( Math.min, 100, [ 5, 3, 7, 2, 6, 5 ] ));

The result was:

undefined

To see what's going on I put:

print( base );

as a first line of the function and the result was:

100
5
3
3
2
2
2
undefined

Whould anyone explain me why?

Was it helpful?

Solution

In that else block, you'll have to

return rec_reduce( ... )

OTHER TIPS

Another way to do it:

reduce_file.js:

function reduce(arr, func, initv){
      if(arr.length) return reduce(arr.slice(1), func, func(initv, arr[0]))
      else return initv
}
module.exports = reduce

and then you use it as:

reduce = require('./reduce_file.js')
console.log(reduce([1,2,3,4], function(prev, curr) {
  return prev + curr
}, 0))

result:

10 

from 1+2+3+4=10

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top