Skip to content

Commit 7ab965f

Browse files
committed
feat: 🎸 add pipe utility
same as ramda's pipe
1 parent 5aaf21e commit 7ab965f

2 files changed

Lines changed: 50 additions & 2 deletions

File tree

index.js

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const curry2 = f => (...a) => (...b) => f(...a, ...b)
66

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

27+
/**
28+
* Compose functions left to right as in ramda's `pipe`.
29+
*
30+
* @param {...Function} fns - functions `(f1, f2, ..., fn)`.
31+
* @returns {*} `pipe(...fns)`
32+
* - Composite function `(...args) => fn(...f2(f1(...args))...)`.
33+
*
34+
* @example
35+
* pipe((a,b)=>a+b, x=>x*2)
36+
* // is equivalent to
37+
* (a,b)=>(a+b)*2
38+
*
39+
*/
40+
const pipe = (...fns) => (...args) => pipeline(...args)(...fns)
2741

2842

2943
/* ----- CPS operators ----- */
@@ -318,6 +332,6 @@ const node2cps = nodeApi => (...args) => CPS(
318332
)
319333

320334
module.exports = {
321-
curry2, pipeline,
335+
curry2, pipeline, pipe,
322336
of, ofN, map, chain, filter, scan, scanS, ap, lift2, CPS, node2cps
323337
}

test/pipe.test.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const test = require('./config')
2+
const { pipe } = require('..')
3+
4+
test('pass single argument to single function', t => {
5+
t.is(pipe(x => x + 2)(1), 3)
6+
})
7+
8+
test('pass multiple arguments to single function', t => {
9+
t.is(pipe(
10+
(x, y) => x + y
11+
)(1, 5), 6)
12+
t.is(pipe(
13+
(x, y, z) => x + y - z
14+
)(1, 2, 5), -2)
15+
})
16+
17+
test('chain multiple functions with single argument', t => {
18+
t.is(pipe(
19+
x => x + 1,
20+
y => y - 2
21+
)(2), 1)
22+
t.is(pipe(
23+
x => x + 1,
24+
y => y - 2,
25+
z => z * 2
26+
)(2), 2)
27+
})
28+
29+
test('chain multiple functions with multiple args', t => {
30+
t.is(pipe(
31+
(x, y) => x + y,
32+
z => z * 2
33+
)(1, 3), 8)
34+
})

0 commit comments

Comments
 (0)