The method is never called...
Most probably the intention is to be able to call it from the top level. Instead of:
show(count(equals(0), [2, 4, 5, 0, 3, 0, 0, 3]));
you could have
var a = [1,4,5,0];
show( countZeroes( a ) );
Question
I can't seem to figure out what the actual importance is for including the following block of code in an exercise in Chapter 6 of Eloquent Javascript.
Edit: It's not needed but rather there to allow for calling it from the top level.
function countZeroes(array) {
return count(equals(0), array);
}
Here is the full code:
function count(test, array) {
return reduce(function(total, element) {
return total + (test(element) ? 1 : 0);
}, 0, array);
}
function equals(x) {
return function(element) {return x === element;};
}
function countZeroes(array) {
return count(equals(0), array);
}
Here is the reduce function from earlier:
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element);
});
return base;
}
Here is the forEach function from earlier:
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
I've only just begun learning JavaScript so I'm sure there is a simple explanation for this. Thanks.
Solution
The method is never called...
Most probably the intention is to be able to call it from the top level. Instead of:
show(count(equals(0), [2, 4, 5, 0, 3, 0, 0, 3]));
you could have
var a = [1,4,5,0];
show( countZeroes( a ) );
OTHER TIPS
Because the function countZeros
never called.
I think the native function Array.filter is better/faster.
function count (whatToCount, theArrayToCount) {
return theArrayToCount.filter (function (element) {
// If they are same, keep; Otherwise remove from array
return element === whatToCount;
}).length; // Count the "filtered" Array, and return it.
}
count (0, [2, 4, 5, 0, 3, 0, 0, 3]); // 3
btw, the callbacks are confusing (..