Sanctuary 雖然有提供 Just
與 Nothing
回傳 Maybe,卻沒有辦法將任何 Value 直接轉成 Maybe,Wink-fp 特別提供 toMaybe
。
Version
Wink-fp 1.28.5
toMaybe
import { isNil } from 'ramda'
import { Just, ifElse } from 'sanctuary'
import { N } from 'wink-fp'
let toMaybe = ifElse (isNil) (N) (Just)
toMaybe (2) // ?
toMaybe (null) // ?
toMaybe (undefined) // ?
第 5 行
let toMaybe = ifElse (isNil) (N) (Just)
特別使用 ifElse
搭配 isNil
判斷,若為 null
或 undefined
則回傳 Nothing,否則回傳 Just。
Wink-fp
import { toMaybe } from 'wink-fp'
toMaybe (undefined) // ?
toMaybe (null) // ?
toMaybe (2) // ?
Wink-fp 已經提供 toMaybe
可直接使用。
toMaybe :: a -> Just | Nothing
將任意 value 轉型成 Just 或 Nothing
a
:傳入任意型別值
Just | Nothing
:回傳 Just 或 Nothing
find
import { find as _find } from 'ramda'
import { pipe, equals, maybe, I } from 'sanctuary'
import { toMaybe } from 'wink-fp'
let find = f => pipe ([
_find (f),
toMaybe
])
let data = [1, 2, 3]
pipe ([
find (equals (5)),
maybe ('N/A') (I)
]) (data) // ?
第 5 行
let find = f => pipe ([
_find (f),
toMaybe
])
使用 pipe
組合回傳 Maybe 的 find
:
_find (f)
:Ramda 的find
是典型會回傳undefined
的 function,特別 alias 為_find
toMaybe
:將_find
回傳值轉成 Maybe
find
相當於 Sanctuary 的find
12 行
pipe ([
find (equals (5)),
maybe ('N/A') (I)
]) (data) // ?
使用 pipe
組合 IIFE:
find (equals (5))
:使用自行組合的find
maybe ('N/A') (I)
:因為回傳 Maybe,需使用maybe
解開
Conclusion
toMaybe
曾經內建於 Sanctuary,後來因故從 Sanctuary 中移除,特別在 Wink-fp 提供toMaybe