TypeScript Maybe Monad 구현

type Maybe<T> = Just<T> | Nothing

class Just<T> {
  constructor(public value: T) {}
  bind<U>(fn: (value: T) => Maybe<U>): Maybe<U> {
    return fn(this.value)
  }
}

class Nothing {
  bind<U>(fn: (value: any) => Maybe<U>): Maybe<U> {
    return this
  }
}

const nothing = new Nothing()

function safeDivide(x: number, y: number): Maybe<number> {
  return y === 0 ? nothing : new Just(x / y)
}

new Just(10).bind((x) => safeDivide(x, 2)) // Just { value: 5 }
new Just(10).bind((x) => safeDivide(x, 0)) // Nothing {}
#535