Search⌘ K

Solution Review: Working with Either and Pipe

Explore how to apply fp-ts functions Either and pipe in a user registration context. Understand how to validate input and transform data using functional programming techniques to write robust, adaptable TypeScript code.

We'll cover the following...

Solution

Let’s see how we use the Either and pipe() functions in the below code.

C++
const checkValidHour = (hour: number): E.Either<string, number> => {
return hour > 0 && hour <= 24 ? E.right(hour) : E.left('invalid hour');
};
const mapToGreeting = (hour: number) => {
return hour < 12 ? 'good morning' : 'good afternoon';
};
const application = (hour: number) => {
return pipe(
checkValidHour(hour),
h => E.map(mapToGreeting)(h),
E.getOrElse(() => 'unknown greeting'),
);
};
console.log(application(8));
console.log(application(13));
console.log(application(25));
...