diff --git a/src/06-challenges/33-compose.solution.ts b/src/06-challenges/33-compose.solution.ts index 60a5cf4..03135cc 100644 --- a/src/06-challenges/33-compose.solution.ts +++ b/src/06-challenges/33-compose.solution.ts @@ -1,40 +1,36 @@ import { expect, it } from "vitest"; import { Equal, Expect } from "../helpers/type-utils"; -export function compose(func: (t1: T1) => T2): (t1: T1) => T2; -export function compose( - func1: (t1: T1) => T2, - func2: (t2: T2) => T3 -): (t1: T1) => T3; -export function compose( - func1: (t1: T1) => T2, - func2: (t2: T2) => T3, - func3: (t3: T3) => T4 -): (t1: T1) => T4; -export function compose( - func1: (t1: T1) => T2, - func2: (t2: T2) => T3, - func3: (t3: T3) => T4, - func4: (t4: T4) => T5 -): (t1: T1) => T5; -export function compose(...funcs: Array<(input: any) => any>) { - return (input: any) => { - return funcs.reduce((acc, fn) => fn(acc), input); +type middleFuncArray = Array<(input: TInput) => TReturn>; + +type FuncArray = [ + (input: TInputFirst) => TReturn, + ...middleFuncArray, + (input: TReturn) => TReturnLast +]; + +export const compose = + ( + ...funcs: FuncArray + ) => + (input: TInputFirst) => { + return funcs.reduce((acc, fn) => fn(acc), input) as TReturnLast; }; -} const addOne = (num: number) => { return num + 1; }; -const addTwoAndStringify = compose(addOne, addOne, String); - -const stringifyThenAddOne = compose( - // @ts-expect-error - String, - // addOne takes in a number - so it shouldn't be allowed after - // a function that returns a string! - addOne +const addTwoAndStringify = compose( + addOne, + addOne, + addOne, + addOne, + addOne, + addOne, + addOne, + addOne, + String ); it("Should compose multiple functions together", () => { @@ -44,3 +40,13 @@ it("Should compose multiple functions together", () => { type tests = [Expect>]; }); + +it("Should error when the input to a function is not typed correctly", () => { + const stringifyThenAddOne = compose( + // addOne takes in a number - so it shouldn't be allowed after + // a function that returns a string! + // @ts-expect-error + String, + addOne + ); +});