From 209706b70d51d8956c35b5d69f6dd455e1f5eaa3 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Mon, 22 Feb 2021 14:31:48 +0100 Subject: [PATCH] feat(compose): forwards this to all functions --- @vates/compose/USAGE.md | 4 +++- @vates/compose/index.js | 4 ++-- @vates/compose/index.spec.js | 26 +++++++++++++++++++------- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/@vates/compose/USAGE.md b/@vates/compose/USAGE.md index 176469f3f..53cde5e99 100644 --- a/@vates/compose/USAGE.md +++ b/@vates/compose/USAGE.md @@ -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 diff --git a/@vates/compose/index.js b/@vates/compose/index.js index c70fefc9f..bf2c03b81 100644 --- a/@vates/compose/index.js +++ b/@vates/compose/index.js @@ -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 } diff --git a/@vates/compose/index.spec.js b/@vates/compose/index.spec.js index a79098e7d..82b7baab8 100644 --- a/@vates/compose/index.spec.js +++ b/@vates/compose/index.spec.js @@ -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) }) })