feat(compose): right to left support

This commit is contained in:
Julien Fontanet 2021-02-18 11:24:39 +01:00
parent 0ec0e286ba
commit 2b91d4af99
3 changed files with 39 additions and 2 deletions

View File

@ -16,3 +16,15 @@ Functions may also be passed in an array:
```js
const f = compose([add2, mul3])
```
Options can be passed as first parameters:
```js
const f = compose(
{
// compose from right to left
right: true,
},
[add2, mul3]
)
```

View File

@ -1,9 +1,21 @@
'use strict'
exports.compose = function compose(fns) {
if (!Array.isArray(fns)) {
const defaultOpts = { right: false }
exports.compose = function compose(opts, fns) {
if (Array.isArray(opts)) {
fns = opts
opts = defaultOpts
} else if (typeof opts === 'object') {
opts = Object.assign({}, defaultOpts, opts)
if (!Array.isArray(fns)) {
fns = Array.prototype.slice.call(arguments, 1)
}
} else {
fns = Array.from(arguments)
opts = defaultOpts
}
const n = fns.length
if (n === 0) {
throw new TypeError('at least one function must be passed')
@ -11,6 +23,11 @@ exports.compose = function compose(fns) {
if (n === 1) {
return fns[0]
}
if (opts.right) {
fns.reverse()
}
return function (value) {
for (let i = 0; i < n; ++i) {
value = fns[i](value)

View File

@ -18,4 +18,12 @@ describe('compose()', () => {
it('accepts functions in an array', () => {
expect(compose([add2, mul3])(5)).toBe(21)
})
it('can apply from right to left', () => {
expect(compose({ right: true }, add2, mul3)(5)).toBe(17)
})
it('accepts options with functions in an array', () => {
expect(compose({ right: true }, [add2, mul3])(5)).toBe(17)
})
})