ES6 Compose function

js.jpg

This is an ES6 function that primarily takes other functions as argument and also returns a function.

This branch of ES6 javascript employs the principle of functional programming (a process of building software composing of pure functions ).

Sample case

we are going write a compose function that takes in two other functions as arguments.

function1 (myName)

const myName = (info) => {
    return `My name is Ikeji chukwunonso, ${info}`;
}

The above piece of code takes in an argument and returns a string concatenated with the parameter.

###function2 (myJob)

const myJob = (job) => {
    return `I am a ${job}`;
}

same as the initial function, this also returns a string.

Compose function

const compose = (fn1,fn2) => {
//return function that will take an argument
    return (arg) => {
         //call function2 with that argument
        const result = fn2(arg);
         //return function1
        return fn1(result);
    }
}

Here our compose function takes in two parameters (myName, myJob), it returns a block of function:

return (arg) => {
        const result = fn2(arg);
        return fn1(result);
    }

This returned function first calls function2 taken the arg argument, whatever it returns is used in function1, what ever function1 now returns, is returned by our function.

const aboutMe = compose(myName,myJob);

Here we have called the compose function and the function returned, is assigned to aboutMe thus making aboutMe a function.

This is same as saying

const aboutMe = (arg) => {
        const result = fn2(arg);
        return fn1(result);
    }

Finally we invoke the function by saying

aboutMe('Software developer');

The above return a string

My name is Ikeji chukwunonso, I am a Software developer

twitter: @techy_lad Github: techyNonso Reference: frontendmasters