Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to apply functional programming in JavaScript

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian introduces in detail "functional programming in JavaScript how to apply", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to apply functional programming in JavaScript" can help you solve your doubts.

Functional programming in JavaScript

Even if functional programming can greatly improve the code of an application, the principle can be challenging at the beginning. Since it will take a lot of time to explain all of this in detail, we decided to use two actual code examples to introduce these concepts.

1.Maybe Monad

In the first example, we found a way to avoid verifying that the variable is Null. Suppose we can find users in our application in the following format:

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

There is a feature that returns a welcome message in the language set by the user.

Const allGreetings = {'en':' Hi', 'sp':' Hello', 'fr':' Welcome'}; const getGreetingForUser = (user) = > {/ / to be executed}

Let's look at the implementation of a "getGreetingForUser" function that follows the imperative model:

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

As you can see above, you must check whether the user already exists, whether the language has been set, and whether the welcome message is ready. If there is a problem, we will return a message in the default language.

Now, let's look at the same function, but this time we will use functional programming in its implementation:

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

To handle situations that may be null or undefined, we will use Maybe Monad. This allows us to create wrappers around objects and assign default behavior to empty objects.

Let's compare two solutions:

/ / instead of verifying whether the user is empty if (! user) {return allGreetings.en } / / We will use: RamdaFantasy.Maybe (user) / / We will add the user to the wrapper / / instead: if (user.settings & & user.settings.language) {if (allGreetings [user.settings.language]) {/ / We will use: .map (Ramda.path (['settings',' language'])) / / if there is data, the mapping will use it / / instead of returning the default value in else: return indexURLs ['en']; .getOrElse (allGreetings. EN) / / the default value specified. 2 Either Monad

Maybe Monad is useful when we know the default behavior when there are null errors.

However, if we have a function that raises an error, or if we link the various functions that cause the error, and we want to know which one failed, we can use Either Monad instead.

Now, let's assume that we want to calculate the price of the product, taking into account VAT and possible discounts. We already have the following code:

Const withTaxes = (tax, price) = > {if (! _ .isNumber (price)) {return new Error ("Price is not numeric");} return price + (tax * price);}; const withDiscount = (dis, price) = > {if (! _ .isNumber (price)) {return new Error ("Price is not numeric");} if (price

< 5) return new Error("Discounts not available for low-priced items"); } return price - (price * dis);5}; const isError = (e) =>

E & & e.name = = 'Error';const calculatePrice (price, tax, discount) = > {/ / to be executed}

Let's look at an implementation of the "calculatePrice" function that follows the imperative model:

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) } / / We calculate the final price of products with a value of 25 (including 21% VAT and 10% discount). CalculatePrice (25,0.21,0.10)

Now, let's see how to rewrite this function using Either Monad.

Both have two constructors, Left and Right. What we want to implement is to store the exception in the Left constructor and the normal result (happiness path) in the Right constructor.

First, you will change the existing withTaxes and withDiscount functions so that they return Left if an error occurs and Right if everything is normal:

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)

Finally, you only need to execute Monad to calculate the final price:

/ / calculate the final price of products with a value of 25 (including 21% VAT and 10% discount). EitherErrorOrPrice (RamdaFantasy.Either.Right (25) .chain (withTaxes (0.21)) .chain (withDiscount (0.1)), this article "how to use functional programming in JavaScript" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it to understand it. If you want to know more about related articles, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report