In this lesson, we'll create a safe function that gives us a flexible-to-create Maybe s based on a value and a Predica Te function that we supply. We ll verify its behavior with the values of that satisfy the predicate, and the values of that does not.
We can write more functional approach, for example write predicate functions:
typeof n = = = ' Number '? typeof s = = = ' String '? Maybe.just (s): maybe.nothing ();
High Order function:
Const SAFE = pred + val== Safe (isstring);
Those functions is useful when we want use on large scale application, because those is composable.
Full Code Demo:
CONST {inc, Upper} = require ('./utils ')); Const maybe= Require (' Crocks/maybe ');Const Isnumber= n + =typeofn = = = ' Number '?maybe.just (N): maybe.nothing (); const isstring= S = =typeofs = = = ' String '?Maybe.just (s): maybe.nothing (); Const safe= Pred = val = =pred (val); Const Safenum=Safe (isnumber); Const SAFESTR=Safe (isstring); Const INPUTN= Safenum (2);//Just 3-3Const InputS = safestr (' test ');//Just Test --TestConst INPUT = safestr (undefined);//Nothing-- 0Const result=InputS. Map (upper). Option (""); Console.log (result);
Crocks Lib also provides those functions, you actually don ' t need to write it by yourself.
Https://evilsoft.github.io/crocks/docs/functions/predicate-functions.html
CONST {inc, Upper} = require ('./utils ')); Const maybe= Require (' Crocks/maybe '); const Safe = Require (' Crocks/maybe/safe '); const { isnumber, isstring}= Require (' crocks/predicates ');/*Const ISNUMBER = n = typeof N = = = ' Number '? Maybe.just (N): maybe.nothing (); Const Isstring = s = = typeof S = = = ' String '? Maybe.just (s): maybe.nothing (); Const SAFE = Pred = val = pred (val);*/Const Safenum=Safe (isnumber); Const SAFESTR=Safe (isstring); Const INPUTN= Safenum (2);//Just 3-3Const InputS = safestr (' test ');//Just Test --TestConst INPUT = safestr (undefined);//Nothing-- 0Const result=InputS. Map (upper). Option (""); Console.log (result);
[Javascript Crocks] Create a maybe with a ' safe ' Utility Function