I'm currently grappling with a piece of functional style code that is featured in the book Eloquent Javascript:
Here's the issue I'm facing: When I have the count() function passing an anonymous function to reduce(), everything seems to work perfectly. However, once I try breaking out the function into a helper function (countHelper()), I encounter a reference error.
If anyone could shed some light on why count() works smoothly while countHelper() throws an error, I would greatly appreciate it!
var numbers = [1,2,3,0,1,2,3,0]
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element);
});
return base;
}
function equals(x) {
return function(element) { return x === element;};
}
function count(test, array) {
return reduce(function(base, element) {
return base + (test(element)?1:0);
}, 0, array);
}
function countHelper(test, array) {
function helper(base, element) {
return base + (test(element)?1:0);
}
return reduce(helper(base, element), 0, array);
}
function countZeroes(array) {
return count(equals(0), array);
}
print(countZeroes(numbers)) // 2
function countZeroesHelper(array) {
return countHelper(equals(0), array);
}
print(countZeroesHelper(numbers)) // ReferenceError: base is not defined