DEV Community

Discussion on: An Adequate Introduction to Functional Programming

Collapse
 
aminnairi profile image
Amin • Edited

Hi there, great article!

Just to be sure everyone is on the same page for the pipe function, I rewrote it using the function keyword and a for...of loop (and human-readable variable names).

"use strict";

function pipe(...functions) {
    // functions === [increment, double, square]

    return function(value) {
        // value === 1

        let finalValue = value;

        for (const getFunctionReturnValueFor of functions) {
            finalValue = getFunctionReturnValueFor(finalValue);
            // finalValue === increment(1) === 2
            // finalValue === double(2) === 4
            // finalValue === square(4) === 16
        }

        return finalValue;
        // finalValue === 16
    }
}

function increment(value) {
    return value + 1;
    // 1 + 1 === 2
}

function double(value) {
    return value * 2;
    // 2 * 2 === 4
}

function square(value) {
    return value ** 2;
    // 4 ** 4 === 16
}

const incDoubleSquare = pipe(increment, double, square);

console.log(incDoubleSquare(1)); // 16
Enter fullscreen mode Exit fullscreen mode

This is just an imperative way of writing what Andrea wrote with the reduce method. Same thing, different way of writing it. Maybe a little more understandable for newcomers with the imperative way. I hope that helped!

Collapse
 
shaibuzach profile image
Shaibu Zachariyya

Thank you.

Collapse
 
uzitech profile image
Tony Brix

Seems kind of ironic that someone would need to write code in an imperative way to make it more readable in an article that claims declarative programming is easier to read. 😂🤣

Collapse
 
aminnairi profile image
Amin

You are correct! I think that when beginners start to see things like map or reduce or findIndex they get lost quicker than when using this way of writing (which uses concepts that are present in other imperative languages). Maybe a little more approachable to begin the smooth transition to the Array methods.

Thread Thread
 
mr_bertoli profile image
Andrea Bertoli • Edited

Thanks Amin for the "human-readable" version of pipe! 😁

The article supposes some degree of familiarity with JS. Maybe I need to mention some prerequisites in the intro part.

Collapse
 
Sloan, the sloth mascot
Comment deleted
 
aminnairi profile image
Amin

You are very welcome friend. I also understand that this topic could last for hours of reading but I think we can agree that we agree. 😂

Anyway great article again I really enjoy reading this through. Keep up the good work!