[Javascript] Maybe Functor

In normal Javascript, we do undefine check or null check:

var person = {age: 14, name: "Suvi"};
var name = person.name ? person.name: null;

Sometime backend data return may contain or not contain 'name' prop.

 

So let's see how to define a Maybe() functor:

var _Maybe.prototype.map = function(f) {
  return this.val ? Maybe(f(this.val)) : Maybe(null);
}

map(capitalize, Maybe("flamethrower"))
//=> Maybe(“Flamethrower”)

The idea of Maybe is check whetehr the Container has value or not, if not return Maybe(null), if has then return Maybe(val).

 

复制代码
// Exercise 3
// ==========
// Use safeGet and _.head to find the first initial of the user

var _ = R;
var P = PointFree;
var map = P.fmap;
var compose = P.compose;
var Maybe = P.Maybe;
var Identity = P.Id;


var safeGet = _.curry(function(x,o){ return Maybe(o[x]) }) var user = {id: 2, name: "Albert"} console.log("--------Start exercise 3--------") var ex3 = compose(map(_.head), safeGet('name')); assertDeepEqual(Maybe('A'), ex3(user)) console.log("exercise 3...ok!")
复制代码

So after the "safeGet('name')" run, it return "Maybe('Albert')";

Then we use map(_.head): map--> get into the Maybe to check val; 

_.head --> Get teh 'A' or 'Albert'.

 

The good thing about this is if use 'safeGet('address')' which inside 'user' object doesn't provide, then we will get 'Maybe(null)':

"Uncaught expected Maybe(A) to equal Maybe(null) (line 68)"

 

复制代码
// Exercise 4
// ==========
// Use Maybe to rewrite ex4 without an if statement
console.log("--------Start exercise 4--------")

var _ = R;
var P = PointFree;
var map = P.fmap;
var compose = P.compose;
var Maybe = P.Maybe;
var Identity = P.Id;

var ex4 = function(n) {
  if(n){
    return parseInt(n);
  }
}

var ex4 = compose(map(parseInt), Maybe)


assertDeepEqual(Maybe(4), ex4("4"))
console.log("exercise 4...ok!")
复制代码

So when the value comes into the ex4 which we wrote, first we will get "Maybe(4)";

Because Maybe(4) is inside a Functor, then we need to call map() on it to get value;

 

posted @   Zhentiw  阅读(425)  评论(0编辑  收藏  举报
编辑推荐:
· 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-07 [Flux] 3. Actions
2015-09-07 [RxJS] Aggregating Streams With Reduce And Scan using RxJS
2015-09-07 [RxJS] map vs flatMap
2015-09-07 [RxJS] Stream Processing With RxJS vs Array Higher-Order Functions
2015-09-07 [MODx] Solve cannot upload large file
点击右上角即可分享
微信分享提示