DEV Community

Cover image for Higher Order Functions from scratch - Functional JS
bhupendra
bhupendra

Posted on

Higher Order Functions from scratch - Functional JS

Why Functional Programming

Functions are first class objects in JavaScript that means functions can be treated as objects as well, functions can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.

function greet() { 
console.log(`Hello ${greet.person}, how are you !`)
}
greet.person = 'Mohit'  // using fn as object
greet() // prints Hello Mohit, how are you !

Functional Programming pattern makes asynchronicity possible in JS , functions are invoked when () is present after variable containing function definition. What if we don't want to run a function immediately but after some delay like setTimeout which takes in two parameters - a callback function and other is delay in ms. This type of function is called Higher Order Function, which is a function that takes in a function as an argument or returns a function. This pattern gives rise to concept of Closures which is the most powerful concept in JS.

Inbuilt High Order Functions in Arrays

JS provides us with many higher order functions like map,reduc,filter,sort ... , this allows functions composition possible which helps us in writing cleaner and maintainable code.

Let's see how we can create few Higher Order functions from scratch :

Map method from scratch

Array.prototype.map -
The map() method creates a new array by calling the callback function provided as an argument on every element in the input array.

Array.prototype.map2 = function(fn) {
    let result = [];
    for (let i = 0, l = this.length; i < l; i++) {
        result.push(fn(this[i]))
    };
    return result;
}
const arr = [1,2,3];
const mulBy2 = (ele) => ele*2;
console.log(arr.map(mulBy2)) // [2,4,6]
console.log(arr.map2(mulBy2)) // [2,4,6]

Filter method form scratch

Array.protoype.filter -
The filter() method creates a new array with all elements that pass the test provided by the callback function.

Array.prototype.filter2 = function(fn) {
    let result = [];
    for (let i=0,l=this.length;i<l;i++) {
        fn(this[i]) && result.push(this[i])
    };
    return result;
}
const arr1 = [1,2,3,5,8];
const getOddNos = (ele) => ele%2 !== 0;
console.log(arr1.filter(getOddNos))  // [1,3,5]
console.log(arr1.filter2(getOddNos)) // [1,3,5]

Reduce method form scratch

Array.prototype.reduce -
The reduce method executes the callback function on each member of the calling array which results in a single output value. The reduce method accepts two parameters: 1) The reducer function (callback), 2) and an optional initialValue.

 Array.prototype.reduce2 = function(fn, acculumator) {
    for (let i = 0, l = this.length; i < l; i++) {
        acculumator = fn(acculumator, this[i])
    };
    return acculumator;
}
const arr2 = [1,2,3,4,5];
const sumSeries = (acculumator,currentValue) => acculumator+currentValue;
console.log(arr2.reduce(sumSeries,0)); // 15
console.log(arr2.reduce2(sumSeries,0)); // 15

Top comments (0)