Functional Programming With Javascript: Pipe, Go

Last time, we prepared ingredient to make pipelining functions. Let’s implement it in earnest.

Pipe

Pipe function ties up pure functions. It takes plural functions, and return a single function. The returned function executes input functions in order.

test('pipe', () => {  const squareOnlyOdds = pipe(    (collection) => filter(collection, value => value % 2),    (collection) => map(collection, value => value * value),  );  expect(squareOnlyOdds([1, 2, 3, 4, 5, 6])).toStrictEqual([1, 9, 25]);});
// functions/pipe/index.jsconst reduce = require('../reduce');
function pipe(...fns) { return (collection) => reduce(fns, (prevResult, fn) => fn(prevResult), collection);}module.exports = pipe;

Go

The pipe function returns a new function that is contains all input functions. Sometimes we want to put the data, excute directly and get return value. In this case, there is a ‘go’ function like this.

test('go', () => {  const squaredOdds = go(    [1, 2, 3, 4, 5, 6],    (collection) => filter(collection, value => value % 2),    (collection) => map(collection, value => value * value),  );  expect(squaredOdds).toStrictEqual([1, 9, 25]);});
const pipe = require('../pipe');function go(collection, ...fns) {  return pipe(...fns)(collection);}module.exports = go;

Use curring

Pipe & Go functions are implemented successfully. Now, we’re going to make codes pritter. Last time, we made curry & curryr. It supports functions to receive iterable and iteratee separately.

test('pipe', () => {  const squareOnlyOdds = pipe(    filter(value => value % 2),    map(value => value * value),  );  expect(squareOnlyOdds([1, 2, 3, 4, 5, 6])).toStrictEqual([1, 9, 25]);});test('go', () => {  const squaredOdds = go(    [1, 2, 3, 4, 5, 6],    filter(value => value % 2),    map(value => value * value),  );  expect(squaredOdds).toStrictEqual([1, 9, 25]);});

woohyun