Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update solution for 33-compose.solution #33

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 34 additions & 28 deletions src/06-challenges/33-compose.solution.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,36 @@
import { expect, it } from "vitest";
import { Equal, Expect } from "../helpers/type-utils";

export function compose<T1, T2>(func: (t1: T1) => T2): (t1: T1) => T2;
export function compose<T1, T2, T3>(
func1: (t1: T1) => T2,
func2: (t2: T2) => T3
): (t1: T1) => T3;
export function compose<T1, T2, T3, T4>(
func1: (t1: T1) => T2,
func2: (t2: T2) => T3,
func3: (t3: T3) => T4
): (t1: T1) => T4;
export function compose<T1, T2, T3, T4, T5>(
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<TInput, TReturn> = Array<(input: TInput) => TReturn>;

type FuncArray<TInputFirst, TReturn, TReturnLast> = [
(input: TInputFirst) => TReturn,
...middleFuncArray<TReturn, TReturn>,
(input: TReturn) => TReturnLast
];

export const compose =
<TInputFirst, TReturn, TReturnLast>(
...funcs: FuncArray<TInputFirst, TReturn, TReturnLast>
) =>
(input: TInputFirst) => {
return funcs.reduce<any>((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", () => {
Expand All @@ -44,3 +40,13 @@ it("Should compose multiple functions together", () => {

type tests = [Expect<Equal<typeof result, string>>];
});

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
);
});