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?
Alberto Zaccagni
31.8k11 gold badges75 silver badges108 bronze badges
asked Jan 11, 2011 at 11:09
trzewiczek
1,8311 gold badge14 silver badges16 bronze badges
2 Answers 2
In that else block, you'll have to
return rec_reduce( ... )
answered Jan 11, 2011 at 11:11
Linus Kleen
34.8k10 gold badges97 silver badges100 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
trzewiczek
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!
Linus Kleen
@trzewiczek Care to accept, then? Suits your profile well, too.
trzewiczek
Sorry about that - it's just I'm not experienced - forgot about that!!
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
answered May 28, 2014 at 21:55
guerrerocarlos
1,42414 silver badges6 bronze badges
Comments
lang-js