Search code examples
javascripthigher-order-functionsfizzbuzz

Need help fixing the output of this Higher Order Function.


function each(arr, fn) {
for(var i = 0; i < arr.length; i++){
    fn(arr[i]);
    }
}


each([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], function(val){
if((val % 3) === 0){
    console.log(val + " fizz");
    } else if((val % 5) === 0) {
    console.log(val + " buzz");
    } else if((val % 15) === 0){
    console.log(val + " fizzbuzz");        
    } else {
    console.log(val);
    }
});

I am trying to get "fizzbuzz" to show up on the 15th element. I'm unsure of what to change to fix this. Any help will be appreciated.


Solution

  • It's not really what you asked, so take it for what it's worth. But since you are looking at higher-order functions, which are generally a feature of functional styles, you might consider taking a functional approach here.

    For example you don't need all the loops and if/thens. Your each function is almost identical to array.map. And your ifs are testing against a set of values, so you could just use filter. Also, when you do this, you will notice that you don't need to check val % 15 because you are already checking 3 and 5:

    function each(arr, fn) { arr.map(fn) } // this is a bit redundanct but I left it to show why
              
    each([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], function(val){
        let words = [
            {n: 3, text: 'fizz'},
            {n: 5, text: 'buzz'},   
        ]
        // now just filter the words array and use reduce to build your string
        let text = words.filter(w => !(val % w.n))
                   .reduce((a, item) => a + item.text  , `${val}: ` )
     
        console.log(text)
            
    })

    It's a different style that takes some getting used to (and it's not always faster), but it has less noise and fits well with other higher order functions.