Skip to content

Commit

Permalink
Merge pull request #1050 from Bjvanminnen/compose
Browse files Browse the repository at this point in the history
composition can be seeded with multiple arguments
  • Loading branch information
gaearon committed Dec 12, 2015
2 parents 1891004 + 422c37a commit 9cd5af4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/utils/compose.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,15 @@
* 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) => {
if (funcs.length === 0) {
// We weren't given any functions, just return the first passed in arg.
return args[0]
}

const last = funcs[funcs.length - 1]
const rest = funcs.slice(0, -1)

return rest.reduceRight((composed, f) => f(composed), last(...args))
}
}
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)
})
})
})

0 comments on commit 9cd5af4

Please sign in to comment.