Skip to content Skip to sidebar Skip to footer

Function Composition With Rest Operator, Reducer And Mapper

I'm following an article about Transducers in JavaScript, and in particular I have defined the following functions const reducer = (acc, val) => acc.concat([val]); const reduceW

Solution 1:

Your more operates with only 2 functions. And the problem is here more(squares,divtwo)(sumOf) you execute a function, and here more(squares,divtwo, sumOf) you return a function which expects another call (fo example const f = more(squares,divtwo, sumOf); f(args)).

In order to have a variable number of composable functions you can define a different more for functions composition. Regular way of composing any number of functions is compose or pipe functions (the difference is arguments order: pipe takes functions left-to-right in execution order, compose - the opposite).

Regular way of defining pipe or compose:

constpipe = (...fns) => x => fns.reduce((v, fn) =>fn(v), x);

constcompose = (...fns) => x => fns.reduceRight((v, fn) =>fn(v), x);

You can change x to (...args) to match your more definition.

Now you can execute any number of functions one by one:

constpipe = (...fns) => x => fns.reduce((v, fn) =>fn(v), x);

constcompose = (...fns) => x => fns.reduceRight((v, fn) =>fn(v), x);

constinc = x => x + 1;
consttriple = x => x * 3;
constlog = x => { console.log(x); return x; } // log x, then return x for further processing// left to right applicationconst pipe_ex = pipe(inc, log, triple, log)(10);

// right to left applicationconst compose_ex = compose(log, inc, log, triple)(10);

Solution 2:

I still can't replace compose(divtwo,squares)(sumOf) with compose(divtwo,squares,sumOf)

Yes, they are not equivalent. And you shouldn't try anyway! Notice that divtwo and squares are transducers, while sumOf is a reducer. They have different types. Don't build a more function that mixes them up.

If you insist on using a dynamic number of transducers, put them in an array:

[divtwo, squares].reduceRight((t, r) =>t(r), sumOf)

Post a Comment for "Function Composition With Rest Operator, Reducer And Mapper"