Home > Software design >  Easy-to-read way of function composition in Javascript
Easy-to-read way of function composition in Javascript

Time:08-29

I'm a huge fan of functional programming. I strive to use point free notation when I can. However, I often don't understand when point free notation is appropriate or when it is overkill. I typical delema that I run into is when I have a three or fewer functions that I would love to use a compose(...) statement for to avoid creating variables. However, I often feel like the code ends up looking uglier when I use compose(...) for such few functions compared to using intermediate variables.

Here's an example of my dilemma:

// Prefering point free notation
(address, signer, execute) =>
    (atr, sequenceId) =>
        compose(
            setTxHash(atr, sequenceId),
            execute(address, signer),
            findTx,           
        )(atr, sequenceId);
// Preferring temporary variables
(address, signer, execute) =>
    (atr, sequenceId) => {
        const step1 = findTx(atr, sequenceId);
        const step2 = execute(address, signer)(step1);
        const step3 = setTxHash(atr, sequenceId)(step2);
        return step3;
    }
// function composition without using compose(...) method
(address, signer, execute) => (atr, sequenceId) => 
    setTxHash(atr, sequenceId)(
        execute(address, signer)(
            findTx(atr, sequenceId)
        )
    )

I know asking "do any of these look better than others?" may be too subjective but are there any rules of thumb I can use or any good resources that talk about this and can offer a helpful perspective?

Thanks in advance!

CodePudding user response:

If you need to introduce the points (variables with names) anyway because you're passing them to multiple functions, using compose is overkill. The third version of your function is the cleanest in that regard. Also, names are always useful if they are descriptive, since that aids the understandability of the code.

Only if you could write

(execute) => compose(
    setTxHash,
    execute,
    findTx,           
)

the usage of compose gains you anything (in particular, conciseness).

  • Related