Philip Kirkbride
Philip Kirkbride

Reputation: 22889

Using pipe() and compose() functions in JavaScript?

I'm reading through a book that is discussing built in JavaScript functions compose() and pipe() for combining functions in functional style programming.

One of the examples seems to suggest running the following as front-end code:

const shuffle =
    (deck, randomizer) => {
        const doShuffle = pipe(
            addRandom(randomizer),
            sortByRandom,
            map(card => card.card)
        );
        return doShuffle(deck);
    };

But when I try running it in the Google Developer console I get back an error saying:

Uncaught ReferenceError: pipe is not defined

I've also tried in Firefox with the same results. What version of JavaScript is needed to make use of these functions?

Am I right to think these functions can only be used with node.js or some kind of pre-compiler like Babel?

Note: I'm running Ubuntu and have tried Chromium and Firefox.

Upvotes: 6

Views: 2083

Answers (1)

Jay Kariesch
Jay Kariesch

Reputation: 1482

pipe and compose aren't native functions. You'll have to add them to your javascript document in order to utilize them. This is an ES6 pipe function that you can use in modern browsers:

const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x)

Here's a compose function:

const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);

Upvotes: 8

Related Questions