Skip to content

Commit

Permalink
feat: 🎸 add pipe utility
Browse files Browse the repository at this point in the history
same as ramda's pipe
  • Loading branch information
dmitriz committed Dec 23, 2022
1 parent 5aaf21e commit 7ab965f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
18 changes: 16 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const curry2 = f => (...a) => (...b) => f(...a, ...b)

/**
* Pass tuple of values to sequence of functions similar to UNIX pipe
* `(x1, ..., xn) | f1 | f2 | ... | fm`
* `(x1, ..., xn) | f1 | f2 | ... | fm`.
*
* @param {...*} args - tuple of arbitrary values.
* @param {...Function} fns - functions `(f1, f2, ..., fn)`.
Expand All @@ -24,6 +24,20 @@ const pipeline = (...args) => (...fns) => fns.slice(1).reduce(
fns[0](...args)
)

/**
* Compose functions left to right as in ramda's `pipe`.
*
* @param {...Function} fns - functions `(f1, f2, ..., fn)`.
* @returns {*} `pipe(...fns)`
* - Composite function `(...args) => fn(...f2(f1(...args))...)`.
*
* @example
* pipe((a,b)=>a+b, x=>x*2)
* // is equivalent to
* (a,b)=>(a+b)*2
*
*/
const pipe = (...fns) => (...args) => pipeline(...args)(...fns)


/* ----- CPS operators ----- */
Expand Down Expand Up @@ -318,6 +332,6 @@ const node2cps = nodeApi => (...args) => CPS(
)

module.exports = {
curry2, pipeline,
curry2, pipeline, pipe,
of, ofN, map, chain, filter, scan, scanS, ap, lift2, CPS, node2cps
}
34 changes: 34 additions & 0 deletions test/pipe.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const test = require('./config')
const { pipe } = require('..')

test('pass single argument to single function', t => {
t.is(pipe(x => x + 2)(1), 3)
})

test('pass multiple arguments to single function', t => {
t.is(pipe(
(x, y) => x + y
)(1, 5), 6)
t.is(pipe(
(x, y, z) => x + y - z
)(1, 2, 5), -2)
})

test('chain multiple functions with single argument', t => {
t.is(pipe(
x => x + 1,
y => y - 2
)(2), 1)
t.is(pipe(
x => x + 1,
y => y - 2,
z => z * 2
)(2), 2)
})

test('chain multiple functions with multiple args', t => {
t.is(pipe(
(x, y) => x + y,
z => z * 2
)(1, 3), 8)
})

0 comments on commit 7ab965f

Please sign in to comment.