feat(compose): forwards this to all functions
This commit is contained in:
@@ -11,7 +11,9 @@ console.log(f(5))
|
|||||||
// → 21
|
// → 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
|
```js
|
||||||
const add = (x, y) => x + y
|
const add = (x, y) => x + y
|
||||||
|
|||||||
@@ -32,14 +32,14 @@ exports.compose = function compose(opts, fns) {
|
|||||||
? async function () {
|
? async function () {
|
||||||
let value = await fns[0].apply(this, arguments)
|
let value = await fns[0].apply(this, arguments)
|
||||||
for (let i = 1; i < n; ++i) {
|
for (let i = 1; i < n; ++i) {
|
||||||
value = await fns[i](value)
|
value = await fns[i].call(this, value)
|
||||||
}
|
}
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
: function () {
|
: function () {
|
||||||
let value = fns[0].apply(this, arguments)
|
let value = fns[0].apply(this, arguments)
|
||||||
for (let i = 1; i < n; ++i) {
|
for (let i = 1; i < n; ++i) {
|
||||||
value = fns[i](value)
|
value = fns[i].call(this, value)
|
||||||
}
|
}
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,18 +37,30 @@ describe('compose()', () => {
|
|||||||
).toBe(21)
|
).toBe(21)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('first function receives this and all args', () => {
|
it('forwards all args to first function', () => {
|
||||||
expect.assertions(2)
|
expect.assertions(1)
|
||||||
|
|
||||||
const expectedArgs = [Math.random(), Math.random()]
|
const expectedArgs = [Math.random(), Math.random()]
|
||||||
const expectedThis = {}
|
|
||||||
compose(
|
compose(
|
||||||
function (...args) {
|
(...args) => {
|
||||||
expect(this).toBe(expectedThis)
|
|
||||||
expect(args).toEqual(expectedArgs)
|
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
|
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)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user