Skip to content

Commit 9cd5af4

Browse files
committed
Merge pull request #1050 from Bjvanminnen/compose
composition can be seeded with multiple arguments
2 parents 1891004 + 422c37a commit 9cd5af4

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/utils/compose.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,15 @@
66
* left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))).
77
*/
88
export default function compose(...funcs) {
9-
return arg => funcs.reduceRight((composed, f) => f(composed), arg)
9+
return (...args) => {
10+
if (funcs.length === 0) {
11+
// We weren't given any functions, just return the first passed in arg.
12+
return args[0]
13+
}
14+
15+
const last = funcs[funcs.length - 1]
16+
const rest = funcs.slice(0, -1)
17+
18+
return rest.reduceRight((composed, f) => f(composed), last(...args))
19+
}
1020
}

test/utils/compose.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,17 @@ describe('Utils', () => {
2121
expect(compose(b, c, a)(final)('')).toBe('bca')
2222
expect(compose(c, a, b)(final)('')).toBe('cab')
2323
})
24+
25+
it('can be seeded with multiple arguments', () => {
26+
const square = x => x * x
27+
const add = (x, y) => x + y
28+
expect(compose(square, add)(1, 2)).toBe(9)
29+
})
30+
31+
it('returns the first given argument if given no functions', () => {
32+
expect(compose()(1, 2)).toBe(1)
33+
expect(compose()(3)).toBe(3)
34+
expect(compose()()).toBe(undefined)
35+
})
2436
})
2537
})

0 commit comments

Comments
 (0)