JSFiddle - React, Tailwind, and code Playground

by Jihad Dzikri Waspada

Babel + JSX

class Maybe {
  static of(value) {
    if (value === null || value === undefined)
      return new Nothing

    return new Just(value)
  }
  
  flatMap(f) {
    const newMaybe = f(this.value)
    
    if (! (newMaybe instanceof Maybe)) {
      console.error('ERROR! Illegal operation!')
      throw 'Your callback return must be an instance of Monad'
    }

    return newMaybe
  }
}

class Just extends Maybe {
  constructor(value) {
    super()
    this.value = value
  }

  static of(value) {
    return super.of(value)
  }

  map = (f) => Just.of(f(this.value))

  isNothing = () => false

  orElse = (otherMonad) => this

  getOrElse = (otherValue) => this.get()

  get = () => this.value
}

class Nothing extends Maybe {  
  static of(value) {
    return new Nothing
  }

  map = (f) => this

  isNothing = () => true

  orElse = (newValue) => Just.of(newValue)

  getOrElse = (newValue) => newValue

  get = () => null
}

const post = Maybe.of({ title: 'Apik banget pak' })
const res = post
  .map(x => x.body)
  .map(x => `${x}: iki judule`)
  .orElse({ title: 'New Judul' })
  .map(x => null)
  .getOrElse('Nyerah dah!')

console.log(res)