Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

composition can be seeded with multiple arguments #1050

Merged
merged 4 commits into from
Dec 12, 2015
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/utils/compose.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@
* left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))).
*/
export default function compose(...funcs) {
return arg => funcs.reduceRight((composed, f) => f(composed), arg)
return (...args) => {
return funcs.length ?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a little hard to grasp what this is doing at first.
Maybe re-writing this as an if statement would make this function a bit easier to follow.

funcs.slice(0, -1).reduceRight((composed, f) => f(composed), funcs[funcs.length - 1](...args)) :
args[0]
}
}
12 changes: 12 additions & 0 deletions test/utils/compose.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,17 @@ describe('Utils', () => {
expect(compose(b, c, a)(final)('')).toBe('bca')
expect(compose(c, a, b)(final)('')).toBe('cab')
})

it('can be seeded with multiple arguments', () => {
const square = x => x * x
const add = (x, y) => x + y
expect(compose(square, add)(1, 2)).toBe(9)
})

it('returns the first given argument if given no functions', () => {
expect(compose()(1, 2)).toBe(1)
expect(compose()(3)).toBe(3)
expect(compose()()).toBe(undefined)
})
})
})