pifuegtq23
pifuegtq23

Reputation: 171

JavaScript functional programing with compose function and Array.reduce

I am new to JavaScript Functional programming. In code below, compose can't work without setInterval outside it and clear as the first argument also does't give the compose initial value.

So my question is how can compose work without the setInterval?

const clear = () => console.clear()
const f1 = () => 2
const log = message => console.log(message)

const compose = (...fns) =>
    arg =>
        fns.reduce(
            (composed, f) => f(composed),
            arg
        )

setInterval(
    compose(clear, f1, log), 1000
)

Upvotes: 1

Views: 184

Answers (1)

klugjo
klugjo

Reputation: 20885

compose(...fns) returns a function. When used with setInterval, it is being called implicitly by the JavaScript engine.

If you want to use it directly, you can do something like:

const clear = () => console.clear()
const f1 = () => 2
const log = message => console.log(message)

const compose = (...fns) =>
    arg =>
        fns.reduce(
            (composed, f) => f(composed),
            arg
        )

compose(clear, f1, log)();

Upvotes: 3

Related Questions