首页 > 编程语言 > 详细

[Functional Programming] Use a Javascript Array to Construct a Maybe

时间:2020-02-14 10:26:46      阅读:77      评论:0      收藏:0      [点我收藏+]

Much of our code in real life is full of if statements that check the validity of a given input to see if a given computation should be performed. Using the ever popular Maybe construction allows us capture this disjunction in one place, keeping our functions free of similar if statements that can pollute the intention of the function. You do not even need a fancy library to get this benefit, as Javascript ships with everything you need with it‘s build in Array.

 

const compose = (f, g) => x => f(g(x));

const maybe = pred => x => pred(x) ? [x]: [];
const mapMaybe = fn => m => m.map(fn);
const optionMaybe = def => m => m.length > 0 ? m[0]: def;

///////////
const add = a => b => a + b;
const pow = a => a * a;
const isValid = x => typeof x === ‘number‘ && !Number.isNaN(x);

///////////
const doMath = compose(
  pow,
  add(10)
)
const safeDoMath = compose(
  mapMaybe(doMath),
  maybe(isValid)
);
const option = (def) => compose(
  optionMaybe(def),
  safeDoMath
)
const app = option(‘Not a number‘)

//////////
const result = app();

console.log(result)

  

[Functional Programming] Use a Javascript Array to Construct a Maybe

原文:https://www.cnblogs.com/Answer1215/p/12306147.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!