Either represents a value that is one of two things: a Right (success) or a Left (failure/error).
Unlike Maybe, Left carries information about what went wrong.
function parseAge(str) {
const n = parseInt(str, 10);
if (isNaN(n) || n < 0 || n > 150) return Left.of('Invalid age: ' + str);
return Right.of(n);
}
parseAge('25').map(age => age * 2).fold(err => -1, val => val); // 50
parseAge('abc').map(age => age * 2).fold(err => -1, val => val); // -1Implement Right and Left classes, each with:
static of(value).map(fn) — Right applies fn, Left ignores it.fold(leftFn, rightFn) — calls the appropriate functionSample tests