JavaScript是一种发展趋势快速的语言表达。在这篇文章中,我觉得展现一些有关怎样在JavaScript中运用函数式编程的事例。

JavaScript中的函数式编程。

虽然函数式编程能够很大地改善运用编程代码,但其基本原理在进行时很有可能有一些趣味性。因为详尽表述全部这种必须耗费很多時间,我们决定应用2个具体的代碼实例来详细介绍这种定义。

js判断空对象的方法-foreach跳出本次循环-第1张图片1.或许是订单

在第一个事例中,大家找到一种防止认证自变量是不是为空的方式。假定在人们的应用软件中,我们可以寻找具备下列文件格式的客户:

const someUser = { name: 'some_name', email: 'some@email.com', settings: { language: 'sp' }};

有一个以客户设定的语言表达回到热烈欢迎信息的作用。

const allGreetings = { 'en': '嗨', 'sp': '您好', 'fr': '欢迎您'};const getGreetingForUser = (user) => { //即将实行}

看一下遵循指令实体模型的“getGreetingForUser”涵数的完成:

const getGreetingForUser = (user) => { if (!user) { return allGreetings.en; } if (user.settings && user.settings.language) { if (allGreetings[user.settings.language]) { return allGreetings[user.settings.language] } else { return allGreetings.en; } } else { return allGreetings.en; }};console.log(getGreetingForUser(someUser));

如上所述,必须检查用户是不是早已存有,语言表达是不是早已设定,热烈欢迎信息是不是早已准备好。假如有什么问题,大家将以默认设置语言表达回到信息。

如今,使我们看一下同样的涵数,但此次大家将在它的完成中应用函数式编程:

const getGreetingForUser = (user) => { return RamdaFantasy.Maybe(user) .map(Ramda.path(['settings', 'language'])) .chain(maybeGreeting);};const maybeGreeting = Ramda.curry((greetingsList, userLanguage) => { return RamdaFantasy.Maybe(greetingsList[userLanguage]);})(allGreetings);console.log(getGreetingForUser(someUser).getOrElse(allGreetings.en));

为了更好地解决很有可能为空或未定义的状况,大家将应用或许订单。这容许我们在目标周边建立包裝器,并将默认设置个人行为分派给空目标。

js判断空对象的方法-foreach跳出本次循环-第2张图片使我们较为二种解决方法:

//替代认证客户是不是为空if (!user) { return allGreetings.en;}//大家将用:RamdaFantasy.Maybe(user) //大家将客户加上到包裝器中//替代: if (user.settings && user.settings.language) { if (allGreetings[user.settings.language]) {//大家将用: .map(Ramda.path(['settings', 'language'])) //假如存有数据信息,投射可能用它//并不是在else中回到初始值: return indexURLs['en'];.getOrElse(allGreetings。EN)// 特定的初始值。

2任一订单

在我们了解发生空不正确时的默认设置个人行为时,或许Monad十分有效。

殊不知,如果我们有一个造成不正确的涵数,或是如果我们将造成不正确的一些涵数连接在一起,而且大家想要知道哪一个失败了,我们可以应用One Monad来替代。

js判断空对象的方法-foreach跳出本次循环-第3张图片如今,使我们假定咱们想测算商品的价钱,考虑到所得税和很有可能的折扣优惠。大家早已有下列编码:

const withTaxes = (tax, price) => {2 if (!_.isNumber(price)) {3 return new Error("Price is not numeric");4 }5 return price (tax * price);6};7const withDiscount = (dis, price) => { 8 if (!_.isNumber(price)) { 9 return new Error("Price is not numeric"); 10 } 11 if (price < 5) 12 return new Error("Discounts not available for low-priced items"); 13 } 14 return price - (price * dis);5}; const isError = (e) =>e && e.name === '不正确';变量定义测算价钱(价钱,税款,折扣优惠)= > {//待实行}使我们看一下遵循命令句实体模型的“测算价钱”涵数的完成:

const calculatePrice = (price, tax, discount) => { const priceWithTaxes = withTaxes(tax, price); if (isError(priceWithTaxes)) { return console.log('Error: ' priceWithTaxes.message); } const priceWithTaxesAndDiscount = withDiscount(discount, priceWithTaxes); if (isError(priceWithTaxesAndDiscount)) { return console.log('Error: ' priceWithTaxesAndDiscount.message); } console.log('Total Price: ' priceWithTaxesAndDiscount);}//大家测算出使用价值25的商品(含21%的所得税和10%的折扣优惠)的最后价钱。 calculatePrice(25, 0.21, 0.10)

如今,使我们学习培训怎么使用任一订单调用这一涵数。

有两个构造方法,左和右。大家要想完成的是在左构造方法中储存出现异常,在右构造方法中储存一切正常結果(开心途径)。

最先,目前的withTaxes和withDiscount涵数将被变更,那样当发生不正确时,他们将回到到左,当一切正常时,他们将回到到右。

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)); });

随后,大家为右例建立一个涵数(表明价钱),为左例建立另一个涵数(表明不正确),随后应用他们建立一个任一订单:

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中的函数式编程。

如同大家所看见的,一旦编码被或许和任一目录溶解,它就没那样繁杂了。假如应用恰当,他们能够使人们的编码更非常容易阅读文章和维护保养。

唯一的不就是大家必须摆脱的最开始阻碍,但这能够利用互联网技术上的一些事例和一些检测来完成。

评论(0条)

刀客源码 游客评论