zoukankan      html  css  js  c++  java
  • [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(/..../)
      )
  • 相关阅读:
    C++顺序性容器、关联性容器与容器适配器
    Groovy与Java集成常见的坑--转
    selenium打开chrome浏览器代码
    分组密码的工作模式--wiki
    linux下C语言多线程编程实例
    C语言多线程pthread库相关函数说明
    C语言使用pthread多线程编程(windows系统)二
    C语言使用pthread多线程编程(windows系统)一
    使用_beginThreadex创建多线程(C语言版多线程)
    浅谈C语言中的联合体
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6175759.html
Copyright © 2011-2022 走看看