From 052e591e21b719482431c833fdeef619b0642057 Mon Sep 17 00:00:00 2001 From: D_MENT <44676701+rocket111185@users.noreply.github.com> Date: Thu, 25 Mar 2021 12:44:44 +0200 Subject: [PATCH] Create solution 1-pipe in TypeScript The example shows that TypeScript allows you to define the contract so you don't have to check the types implicitly. --- Solutions/1-pipe.ts | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Solutions/1-pipe.ts diff --git a/Solutions/1-pipe.ts b/Solutions/1-pipe.ts new file mode 100644 index 0000000..d4b0fee --- /dev/null +++ b/Solutions/1-pipe.ts @@ -0,0 +1,33 @@ +'use strict'; + +// Define the type "function, that takes one argument +// and returnes the value of the same type" +type oneArg = (arg: T) => T; + +// Construct the "pipe" so it suits the exercise requirements +const pipe = (...fns: oneArg[]): oneArg => + x => fns.reduce((v, f) => f(v), x); + + +// Usage + +const inc = (x: number) => ++x; +const twice = (x: number) => x * 2; +const cube = (x: number) => Math.pow(x, 3); + +// You cannot do: +// +// const wrongFunc = x => 'someString'; +// pipe(inc, twice, wrongFunc); + +// Also you cannot do: +// +// const wrongFunc = (x, y) => x + y; +// pipe(inc, twice, wrongFunc); + +// Because wrongFunc does not suit the type +// (arg: T) => T + +const f = pipe(inc, twice, cube); +console.log(f(5)); +