MediumJavaScriptTypeScript

Either Monad

Functional ProgrammingMonadsEitherError Handling

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); // -1

Implement Right and Left classes, each with:

  • static of(value)
  • .map(fn) — Right applies fn, Left ignores it
  • .fold(leftFn, rightFn) — calls the appropriate function

Sample tests

Test #1parseAge("25").map(n=>n*2) = Right(50) → 50
Input: ["25","double"]
Output: 50
Test #2parseAge("abc") = Left → fold returns -1
Input: ["abc","double"]
Output: -1
Test #3parseAge("20").map(n>=18) = Right(true)
Input: ["20","isAdult"]
Output: true
Test #4parseAge("15").map(n>=18) = Right(false)
Input: ["15","isAdult"]
Output: false