首先,将更改已经存在的withTaxes和withDiscount函数,以便在出现错误时它们返回Left,在一切正常的情况下返回Right:
const withTaxes = Ramda.curry((tax, price) => {if (!_.isNumber(price)) {return RamdaFantasy.Either.Left(new Error("Price is not numeric"));}return RamdaFantasy.Either.Right(price + (tax * price)); });const withDiscount = Ramda.curry((dis, price) => {if (!_.isNumber(price)) {return RamdaFantasy.Either.Left(new Error("Price is not numeric"));}if (price < 5) {return RamdaFantasy.Either.Left(new Error("Discounts not available for low-priced items"));}return RamdaFantasy.Either.Right(price - (price * dis)); });
然后,我们为Right案例创建一个函数(显示价格),为Left案例创建另一个函数(显示错误),然后使用它们创建Either Monad:
const showPrice = (total) => { console.log('Price: ' + total) }; const showError = (error) => { console.log('Error: ' + error.message); }; const eitherErrorOrPrice = RamdaFantasy.Either.either(showError, showPrice);最后,只需要执行Monad来计算最终价格:
//计算出价值25的产品(含21%的增值税和10%的折扣)的最终价格 。eitherErrorOrPrice(RamdaFantasy.Either.Right(25).chain(withTaxes(0.21)).chain(withDiscount(0.1)))结论:JavaScript中的函数式编程正如我们所看到的,一旦用Maybe和Either单子分解了代码,就没有那么复杂了 。如果使用得当,它们可以使我们的代码更易于阅读和维护 。
【JavaScript中的函数式编程】
推荐阅读
- 如何将PDF中的文字提取出来!原来PDF提取文字这么简单,看完涨知识了
- 深入JavaScript教你内存泄漏如何防范
- 科学管理Linux系统中的组与组成员
- JavaScript的Array.flat函数深入探讨
- 吉祥生肖指哪个生肖?
- 茶道中的佛典与禅语,茶道与茶艺美学
- 传说中的普洱金瓜贡茶,传说中炎帝神农氏茶的发现者
- 独龙族饮茶定亲的茶俗,四川民俗中的茶俗谚语介绍
- 绿茶中的“火药弹”_平水珠茶
- 一文彻底搞懂JavaScript 中Object.freeze与Object.seal的用法
