[JS Compse] 4. A collection of Either examples compared to imperative code

For if..else:

复制代码
const showPage() {
  if(current_user) {
    return renderPage(current_user);
  } else {
    return showLogin();
  }
}

const showPage() {
  fromNullable(current_user)
    .fold(showLogin, renderPage)
}
复制代码

 

复制代码
const getPrefs = user => {
  if(user.premium) {
    return loadPrefs(user.preferences)
  } else {
    return defaultPrefs;
  }
}

const getPrefs = user => 
  (user.premium ? Right(user): Left('not premium'))
  .map(p => user.preferences)
  .fold(
    x => defaultPrefs,
    x => loadPrefs(x)
  )
复制代码

 

复制代码
const streetName = user => {
  const address = user.address;
  
  if(address) {
    const street = address.street;
    
    if(street) {
      return street.name;
    }
  }
  return 'no street';
}

cosnt streetName = user => 
  fromNullable(user.address)
    .flatMap(address => fromNullable(address.street))
    .map(street => street.name)
    .fold(e => 'no street', n => n)
    
复制代码

 

const concatUniq = (x, ys) => {
  const found = ys.filter(y => y === x)[0]
  return found ? ys : ys.concat(x);
}

const concatUniq = (x, ys) => 
  fromNullable(ys.filter(y => y === x)[0]) // fromNullable needs value
  .fold(() => ys.concat(x), y => ys)

 

复制代码
const wrapExamples = example => {
  if(example.previewPath){
    try {
      example.preview = fs.readFileSync(example.previewPath)
    } catch(e) {
      
    }
    
    return example;
  }
}

const readFile = x => tryCatch(() => readFileSync(x));
const wrapExample = example => 
  fromNullabel(exampe.previewPath)
  .flatMap(readFile)
  .fold(() => example,
         ex => Object.assign({preview: p}, ex);
       )
复制代码

 

复制代码
const parseDbUrl = cfg => {
  try {
    const c = JSON.parse(cfg);
    if(c.url) {
      return c.url.match(/..../)
    } catch(e) {
      return null
    }
  }
}

const parseDbUrl = cfg => 
  tryCatch(() => JSON.parse(cfg))
  .flatMap(c => fromNullable(c.url))
  .fold(
    e => null,
    u => u.match(/..../)
  )
复制代码

 

posted @   Zhentiw  阅读(244)  评论(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-12-14 [AngularJS] Services, Factories, and Providers -- value & Providers
2015-12-14 [AngularJS] Services, Factories, and Providers -- Service vs Factory
2014-12-14 [MongoDB] Query, update, index and group
点击右上角即可分享
微信分享提示