feat(compose): this and args passed to first function
This commit is contained in:
parent
8455d4a49f
commit
04fd625bde
@ -29,6 +29,19 @@ console.log(f(5))
|
||||
// → 21
|
||||
```
|
||||
|
||||
The first function is called with the context and all arguments of the composed function:
|
||||
|
||||
```js
|
||||
const add = (x, y) => x + y
|
||||
const mul3 = x => x * 3
|
||||
|
||||
// const f = (x, y) => mul3(add(x, y))
|
||||
const f = compose(add, mul3)
|
||||
|
||||
console.log(f(4, 5))
|
||||
// → 27
|
||||
```
|
||||
|
||||
Functions may also be passed in an array:
|
||||
|
||||
```js
|
||||
|
@ -11,6 +11,19 @@ console.log(f(5))
|
||||
// → 21
|
||||
```
|
||||
|
||||
The first function is called with the context and all arguments of the composed function:
|
||||
|
||||
```js
|
||||
const add = (x, y) => x + y
|
||||
const mul3 = x => x * 3
|
||||
|
||||
// const f = (x, y) => mul3(add(x, y))
|
||||
const f = compose(add, mul3)
|
||||
|
||||
console.log(f(4, 5))
|
||||
// → 27
|
||||
```
|
||||
|
||||
Functions may also be passed in an array:
|
||||
|
||||
```js
|
||||
|
@ -29,14 +29,16 @@ exports.compose = function compose(opts, fns) {
|
||||
}
|
||||
|
||||
return opts.async
|
||||
? async function (value) {
|
||||
for (let i = 0; i < n; ++i) {
|
||||
? async function () {
|
||||
let value = await fns[0].apply(this, arguments)
|
||||
for (let i = 1; i < n; ++i) {
|
||||
value = await fns[i](value)
|
||||
}
|
||||
return value
|
||||
}
|
||||
: function (value) {
|
||||
for (let i = 0; i < n; ++i) {
|
||||
: function () {
|
||||
let value = fns[0].apply(this, arguments)
|
||||
for (let i = 1; i < n; ++i) {
|
||||
value = fns[i](value)
|
||||
}
|
||||
return value
|
||||
|
@ -36,4 +36,19 @@ describe('compose()', () => {
|
||||
)(5)
|
||||
).toBe(21)
|
||||
})
|
||||
|
||||
it('first function receives this and all args', () => {
|
||||
expect.assertions(2)
|
||||
|
||||
const expectedArgs = [Math.random(), Math.random()]
|
||||
const expectedThis = {}
|
||||
compose(
|
||||
function (...args) {
|
||||
expect(this).toBe(expectedThis)
|
||||
expect(args).toEqual(expectedArgs)
|
||||
},
|
||||
// add a second function to use the one function special case
|
||||
Function.prototype
|
||||
).apply(expectedThis, expectedArgs)
|
||||
})
|
||||
})
|
||||
|
Loading…
Reference in New Issue
Block a user