Search code examples
javascriptfunctional-programmingcompositionsequencing

Javascript functional composition/sequencing


I'm trying to understand composition and "sequencing" concept in Javascript with an exercise:

Def. "composition" compose(f,g)(x) = f(g(x))

Def. "sequencing" sequence(f,g)(x) = g(f(x)) for more args sequence(f,g)(...args) = g(f(...args))

const sequence2 = (f1, f2) => (...args) => f2( f1(...args) );
const sequence = (f1, ...fRest) => fRest.reduce(sequence2, f1);

const f1 = (a, b) => {
    console.log(`[f1] working on: ${a} and ${b}`);
    return a + b;
}

const f2 = a => `Result is ${a}`;

const sequenceResult = sequence(f1, f1, f2)(1, 2, 5);
console.log(sequenceResult);

The console shows:

[f1] working on: 1 and 2
[f1] working on: 3 and undefined
Result is NaN

It seems that the second function in the sequence can't access the args: there is something I'm missing or it's the wrong approach for dealing with parameters? (The sequence function works for functions without params).

Here the JSFiddle


Solution

  • It seems that the second function in the sequence can't access the args

    Yes, that's normal and expected. According to the definition you gave,

    sequence(f1, f1, f2)(1, 2, 5);
    

    is equivalent to

    f2(f1(f1(1, 2, 5)));
    

    Of course neither f2 nor the outer f1 can access the arguments that are passed to the inner f1.