maybe functor

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

作者: 曾小乱

喜欢写点有意思的东西

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注