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 NothingSample tests