js判断空对象的方法(foreach跳出本次循环)

JavaScript是一种发展迅速的语言。这篇文章,我想展示一些有关如何在JavaScript中应用函数式编程的示例。

JavaScript中的函数式编程

即使函数式编程可以极大地改善应用程序的代码,但其原理在开始时可能会有些挑战。由于详细解释所有这些都将花费大量时间,因此我们决定使用两个实际的代码示例来介绍这些概念

js判断空对象的方法(foreach跳出本次循环)

让我们比较两种解决方案:

//代替验证用户是否为空if (!user) {  return allGreetings.en;}//我们将用:RamdaFantasy.Maybe(user) //我们将用户添加到包装器中
//代替: if (user.settings && user.settings.language) {   if (allGreetings[user.settings.language]) {//我们将用: <userMaybe>.map(Ramda.path(['settings', 'language'])) //如果存在数据,映射将会用它
//不是在else中返回默认值: return indexURLs['en'];.getOrElse(allGreetings。EN)// 指定的默认值。

2 Either Monad

当我们知道存在空错误时的默认行为时,Maybe Monad非常有用。

但是,如果我们有一个引发错误的函数,或者我们将各种引发错误的函数链接在一起,并且我们想知道哪个发生了故障,则可以改用Either Monad。

js判断空对象的方法(foreach跳出本次循环)

现在,让我们假设我们要计算产品的价格,同时考虑增值税和可能的折扣。我们已经有了以下代码:

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 === 'Error';const calculatePrice(price, tax, discount) => { //将要执行}

让我们来看一个遵循命令式模型的“ calculatePrice”函数的实现:

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)

现在,让我们了解如何使用Either Monad重写此函数。

都有两个构造函数,Left和Right。我们要实现的是将异常存储到Left构造函数,并将正常结果(快乐路径)存储到Right构造函数。

首先,将更改已经存在的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单子分解了代码,就没有那么复杂了。如果使用得当,它们可以使我们的代码更易于阅读和维护。

唯一的不便是我们需要克服的初始障碍,但这可以通过在网上一些示例并进行一些测试来完成。

(0)
小多多的头像小多多创始人

相关推荐

发表回复

登录后才能评论