博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Javascript] Either Functor
阅读量:6296 次
发布时间:2019-06-22

本文共 2111 字,大约阅读时间需要 7 分钟。

Either Functor:

// APIRight(val) // resolve the valueLeft(val) // return error message

 

Examples:

map(function(x) { return x + 1; }, Right(2))//=> Right(3)map(function(x) { return x + 1; }, Left(‘some message))//=> Left(‘some message’)
var determineAge = function(user){  return user.age ? Right(user.age) : Left("couldn’t get age");}var yearOlder = compose(map(add(1)), determineAge)yearOlder({age: 22})//=> Right(23)yearOlder({age: null})//=> Left("couldn’t get age")

 

var _ = R;var P = PointFree;var map = P.fmap;var compose = P.compose;var Maybe = P.Maybe;var Identity = P.Id;var Either = folktale.data.Either;var Left = Either.Left;var Right = Either.Right;// Exercise 1// ==========// Write a function that uses checkActive() and showWelcome() to grant access or return the errorconsole.log("--------Start exercise 1--------")var showWelcome = compose(_.add( "Welcome "), _.get('name'))var checkActive = function(user) { return user.active ? Right(user) : Left('Your account is not active')}var ex1 = compose(map(showWelcome), checkActive);assertDeepEqual(Left('Your account is not active'), ex1({active: false, name: 'Gary'}))assertDeepEqual(Right('Welcome Theresa'), ex1({active: true, name: 'Theresa'}))console.log("exercise 1...ok!")// Exercise 2// ==========// Write a validation function that checks for a length > 3. It should return Right(x) if it is greater than 3 and Left("You need > 3") otherwiseconsole.log("--------Start exercise 2--------")var ex2 = function(x) {  if(x){    return x.length > 3 ?         Right(x) :         Left("You need > 3");  }else{    return Left("You need > 3");  }}assertDeepEqual(Right("fpguy99"), ex2("fpguy99"))assertDeepEqual(Left("You need > 3"), ex2("..."))console.log("exercise 2...ok!")// Exercise 3// ==========// Use ex2 above and Either as a functor to save the user if they are validvar save = function(x){ console.log("SAVED USER!"); return x; }var ex3 = compose( map(save), ex2)console.log("--------Start exercise 3--------")assertDeepEqual(Right("fpguy99"), ex3("fpguy99"))assertDeepEqual(Left("You need > 3"), ex3("duh"))console.log("exercise 3...ok!")

 

转载地址:http://pwmta.baihongyu.com/

你可能感兴趣的文章
如何制作一个通用的多系统安装U盘七(Windows相关配置)
查看>>
mysql超大数据库备份
查看>>
我的友情链接
查看>>
Citrix Reciever更改https为http模式
查看>>
linux下忘记mysql root密码
查看>>
nessus国内用户不让免费使用了!
查看>>
配置vsftpd的遇到的坑及搭建虚拟账户
查看>>
关于P2P流量的识别方式
查看>>
Open×××的Linux内核版,鬼魅的残缺 part I:The PROTOCOL
查看>>
UVA 610 Street Directions 双连通分量
查看>>
[PXE] Linux(centos6)中PXE 服务器搭建,PXE安装、启动及PXE理论详解
查看>>
cnetos7安装docker V1.0
查看>>
Bash中的$*和$@的区别
查看>>
MySQL常见错误代码及代码说明
查看>>
Android App定位和规避内存泄露方法研究
查看>>
移动平台还有哪些创业机会
查看>>
ansible之fetch模块
查看>>
ftp虚拟账户配置
查看>>
sql server 2008数据复制
查看>>
EIGRP的AD(管理距离)、AD(宣告距离)、FD(可行距离)
查看>>