class Maybe {
constructor(value) {
this.value = value;
}
// Functor map: applies a function if value is not null/undefined
map(fn) {
if (this.value === null) {
return new Maybe(null);
}
return new Maybe(fn(this.value));
}
// getOrElse: safely extract value with a fallback
getOrElse(defaultValue) {
return this.value === null ? defaultValue : this.value;
}
// static helpers for convenience
static of(value) {
return new Maybe(value);
}
static nothing() {
return new Maybe(null);
}
}
// Example usage:
const maybeNumber = Maybe.of(5)
.map(n => n * 2)
.map(n => n + 1);
console.log(maybeNumber.getOrElse(0)); // Output: 11
const maybeNull = Maybe.of(null)
.map(n => n * 2);
console.log(maybeNull.getOrElse(0)); // Output: 0