Search⌘ K

Solution Review: Adding a Check

Explore how to enhance user registration functions by adding validation checks using fp-ts in TypeScript. Understand how to create conditional logic that ensures inputs meet specific criteria, improving code reliability and robustness in functional programming.

We'll cover the following...

Solution

Let’s add a check in the following code.

TypeScript 3.3.4
// Note that you could also use the fp-ts identity function in getOrElse
const checkValidHour = (hour: number): E.Either<string, number> => {
return hour > 0 && hour <= 24 ? E.right(hour) : E.left('invalid hour');
};
const mapToGreeting = (hour: number): string => {
return hour < 12 ? 'good morning' : 'good afternoon';
};
const checkDecentHour = (hour: number): E.Either<string, number> => {
return hour >= 8 ? E.right(hour) : E.left('way too early');
};
const application = (hour: number) => {
return pipe(
checkValidHour(hour),
E.chain(checkDecentHour),
h => E.map(mapToGreeting)(h),
E.getOrElse(err => err),
);
};
console.log(application(5));
console.log(application(9));

Explanation

Here’s a ...