feat(compose): forwards this to all functions

This commit is contained in:
Julien Fontanet 2021-02-22 14:31:48 +01:00
parent 1bc80eb485
commit 209706b70d
3 changed files with 24 additions and 10 deletions

View File

@ -11,7 +11,9 @@ console.log(f(5))
// → 21
```
The first function is called with the context and all arguments of the composed function:
> The call context (`this`) of the composed function is forwarded to all functions.
The first function is called with all arguments of the composed function:
```js
const add = (x, y) => x + y

View File

@ -32,14 +32,14 @@ exports.compose = function compose(opts, fns) {
? async function () {
let value = await fns[0].apply(this, arguments)
for (let i = 1; i < n; ++i) {
value = await fns[i](value)
value = await fns[i].call(this, value)
}
return value
}
: function () {
let value = fns[0].apply(this, arguments)
for (let i = 1; i < n; ++i) {
value = fns[i](value)
value = fns[i].call(this, value)
}
return value
}

View File

@ -37,18 +37,30 @@ describe('compose()', () => {
).toBe(21)
})
it('first function receives this and all args', () => {
expect.assertions(2)
it('forwards all args to first function', () => {
expect.assertions(1)
const expectedArgs = [Math.random(), Math.random()]
const expectedThis = {}
compose(
function (...args) {
expect(this).toBe(expectedThis)
(...args) => {
expect(args).toEqual(expectedArgs)
},
// add a second function to use the one function special case
// add a second function to avoid the one function special case
Function.prototype
).apply(expectedThis, expectedArgs)
)(...expectedArgs)
})
it('forwards context to all functions', () => {
expect.assertions(2)
const expectedThis = {}
compose(
function () {
expect(this).toBe(expectedThis)
},
function () {
expect(this).toBe(expectedThis)
}
).call(expectedThis)
})
})