JavaScript the Fun Part


functional-programming-javascript

higher-order-function


Higher order functions e.g map, filter, reduce are one of most used functions in JS, and other languages. It is so common that might some do not notice it.

We call a function a higher order function when it works with other functions either as its input value or return value.

Here is a simple filter function that uses a predicate function to run on each loop item. It is a non-curry function.

// a non-curry higher order function
const filter = function( predicate, list ){
    const newArray = [];
    for( let index = 0; index < list.length; ++index ){
        if( predicate( list[ index ], index) ){
            newArray.push( list[ index ] );
        }
    }
    return newArray;
}

And here is the same but also in a curry style.

// a curry version of a higher order function
const filter = function( predicate ){
    return function( list ){
        const newArray = [];
        for( let index = 0; index < list.length; ++index ){
            if( predicate( list[ index ], index) ){
                newArray.push( list[ index ] );
            }
        }
        return newArray;
    }
}

As you can see a higher order function is more general than a curry function and when we have a curry function it means it is already a higher order function.

That is it.


Update: Sat Nov 16 2019 08:35:12 GMT+0330 (Iran Standard Time)