2


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?

2 Answers 2

8

In that else block, you'll have to

return rec_reduce( ... )
Sign up to request clarification or add additional context in comments.

3 Comments

THX A LOT!! I forget about this return thing now and then mainly because every thime I need something recursive I prototype it in Scheme - there's no return statement ;) Thx again!
@trzewiczek Care to accept, then? Suits your profile well, too.
Sorry about that - it's just I'm not experienced - forgot about that!!
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.