[Javascript] Either Functor
Either Functor:
// API Right(val) // resolve the value Left(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 error console.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") otherwise console.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 valid var 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!")
分类:
Javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2015-09-08 [AngularJS + Webpack] Requiring CSS & Preprocessors
2015-09-08 [AngularJS + Webpack] Requiring Templates
2015-09-08 [AngularJS + Webpack] ES6 with BabelJS