I am having trouble with getting an incorrect value from an array flatten function when using functional programming principals to generate the flatten function from a generic reduce function. I believe that this is because there is an issue with the recursion within the call, but am unsure how to move past it as the function signatures for both the working and non working function should be the same.
Thanks for any help.
var data = [['one','two','three'], ['four', 'five', ['six']], 'seven', ['eight', 'nine']];
// here is an example of flatten that works perfectly. it takes an array and reduces
// the internal arrays to a single flat array
function flatten( arr ){
return arr.reduce(function( ret, curr ){
if( Array.isArray( curr ) ){
ret = ret.concat( flatten( curr ) );
} else {
ret.push( curr );
}
return ret;
}, []);
}
// here is what I am trying to achieve. This one combines my reduction functon with the
// functional `reduceWith` function. The code signature is exactly the same, however the
// end result is different.
// `functionalFlatten` does resolve to the correct function inside
var functionalFlatten = reduceWith(function( ret, curr ){
if( Array.isArray( curr ) ){
ret = ret.concat( functionalFlatten( curr ) );
} else {
ret.push( curr );
}
return ret;
}, []);
// this function will return a functional reduction function
function reduceWith( fn, initial ) {
return function _reduceWith( arr ) {
return Array.prototype.reduce.call(arr, fn, initial || []);
}
}
console.log('data', data);
console.log('functionalFlatten', functionalFlatten );
console.log('normal', flatten( data ));
console.log('fuctional', functionalFlatten( data ));
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>