DEV Community

Discussion on: Lenses: The What and How

Collapse
misterwhat profile image
Jonas Winzen Author

This kind of function is a higer order function. Higher order functions are functions, that take a function as parameter or return a function.

function compose(g, f) {
    return function(x) { // returns a function, that expects one parameter
        return g(f(x));
    }
}

compose is a higher order function in both ways: It takes functions (g and f) as parameters and returns a function as result. The returned function is a function, that expects takes a parameter (x) and returns the result of calling g with the result of calling f with x.

Your second question:

const compose = (...fns) => x =>

Yes, this is an array of functions but as parameter spread. Spreading a parameter gives you a so called variadic function. For example:

function example(...args) {
  return `I was called with ${args.length} args: ${args.join(", ")}.`;
}

console.log(example("foo", "bar")); // -> "I was called with 2 args: foo, bar."
console.log(example("a", "b", "c")); // -> "I was called with 3 args: a, b, c."
console.log(example("a", 2, "c")); // -> "I was called with 3 args: a, 2, c."
console.log(example("a", 2, "c", "d")); // -> "I was called with 4 args: a, 2, c, d."

Collapse
kurisutofu profile image
kurisutofu

raaa ... now that you say it, I see the

return function(x)

while when I posted my comment I read it as below in my head ...

function compose(g, f) {
    function(x) { // returns a function, that expects one parameter
        return g(f(x));
    }
}

Sorry about that!
And also, thanks for the detailed explanation! I will go back to your article!