diff --git a/@vates/compose/README.md b/@vates/compose/README.md index aeff941c8..f7247e636 100644 --- a/@vates/compose/README.md +++ b/@vates/compose/README.md @@ -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 diff --git a/@vates/compose/USAGE.md b/@vates/compose/USAGE.md index 5d211a42a..176469f3f 100644 --- a/@vates/compose/USAGE.md +++ b/@vates/compose/USAGE.md @@ -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 diff --git a/@vates/compose/index.js b/@vates/compose/index.js index da9ff7e54..c70fefc9f 100644 --- a/@vates/compose/index.js +++ b/@vates/compose/index.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 diff --git a/@vates/compose/index.spec.js b/@vates/compose/index.spec.js index d31a2caec..a79098e7d 100644 --- a/@vates/compose/index.spec.js +++ b/@vates/compose/index.spec.js @@ -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) + }) })