UNPKG

moy-fp

Version:
53 lines (50 loc) 1.28 kB
/** * Maybe is a Functor, Monad and Applicative * can map * can join * can chain * can ap * always use for dividing value for two typs(null type and no null type) * null value cannot do any notaion, just return Maybe(null) * no null value can do notation, return handled result * also can use like Either Functor do if you'd like(I prefer using Maybe, so no Either here) * you may not need it if you are not sensitive in functional programming */ const Maybe = value => Object.seal( Object.create(null, { value: { value, }, [Symbol.toStringTag]: { value: 'Maybe', }, map: { value: function map(fn){ return this.value === null || this.value === undefined ? this : Maybe.of(fn(this.value)) }, }, join: { value: function join(){ return this.value === null || this.value === undefined ? this : this.value }, }, chain: { value: function chain(fn){ return this.map(fn).join() }, }, ap: { value: function ap(M){ return this.value === null || this.value === undefined ? this : M.map(this.value) }, }, }) ) /** * Functor Maybe => a -> Maybe a */ Maybe.of = Maybe export default Maybe