码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-12-14 07:43:05      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:nullable   rom   ddr   user   map   res   color   not   ret   

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(/..../)
  )

 

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

标签:nullable   rom   ddr   user   map   res   color   not   ret   

原文地址:http://www.cnblogs.com/Answer1215/p/6175759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!