MediumJavaScriptTypeScript

Maybe Monad

Functional ProgrammingMonadsMaybe

The Maybe monad eliminates null checks by wrapping a value that might be absent.

// dirty — null checks scattered everywhere
function getCity(user) {
  if (user && user.address && user.address.city) {
    return user.address.city.toUpperCase();
  }
  return 'UNKNOWN';
}

// clean — chain operations safely
Maybe.of(user)
  .map(u => u.address)
  .map(a => a.city)
  .map(c => c.toUpperCase())
  .getOrElse('UNKNOWN');

Implement a Maybe class with:

  • Maybe.of(value) — wraps a value
  • .map(fn) — applies fn if value is not null/undefined, otherwise stays Nothing
  • .getOrElse(defaultValue) — returns the value or defaultValue if Nothing

Sample tests

Test #1Maybe.of("hello").map(toUpper) = "HELLO"
Input: ["hello","toUpper"]
Output: "HELLO"
Test #2Maybe.of(null).map(toUpper).getOrElse("NOTHING") = "NOTHING"
Input: [null,"toUpper"]
Output: "NOTHING"
Test #3Maybe.of(5).map(x=>x*2) = 10
Input: [5,"double"]
Output: 10
Test #4Maybe.of(null).map(double).getOrElse(-1) = -1
Input: [null,"double"]
Output: -1