Created
September 18, 2021 15:49
-
-
Save sushruth/bb441cee19c32ac1726d975d339018aa to your computer and use it in GitHub Desktop.
Another type safe pipe equivalent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Pipeable<I> { | |
constructor(public value: I) {} | |
public pipe<O>(fn: (input: I) => O) { | |
const output = fn(this.value); | |
return { | |
p: new Pipeable(output).pipe, | |
value: output, | |
}; | |
} | |
} | |
export function pipe<T>(input: T) { | |
return new Pipeable(input).pipe(v => v); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const result = pipe(2) | |
.p(v => v * v) | |
.p(v => v.toString()) | |
.p(v => v.toUpperCase()) | |
.value; // result is now string | |
// Compared with - | |
const result = 2 | |
|> (v => v * v) | |
|> (v => v.toString()) | |
|> (v => v.toUpperCase()); // result is now string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment