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

What are the higher-order functions, Corialization and Combinatorial functions in JavaScript

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this issue, the editor will bring you about the high-order functions and Coriarization of JavaScript as well as what the combinatorial functions are like. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

Object-oriented programming and functional programming are two very different programming paradigms, and they have their own rules, advantages and disadvantages.

However, instead of following a rule all the time, JavaScript is right in the middle of these two rules, providing some aspects of the normal OOP language, such as classes, objects, inheritance, and so on. But at the same time, it also provides you with some concepts of functional programming, such as higher-order functions and the ability to combine them.

Higher order function

The most important of the three concepts of everyone in our line: higher-order functions.

Higher-order functions mean that functions are not just functions that can be defined and called from code; in fact, you can use them as assignable entities. This is not surprising if you have used some JavaScript. It is very common to assign anonymous functions to constants.

Const adder = (a, b) = > {return a + b}

The above logic is invalid in many other languages, and being able to allocate a function like an integer is a very useful tool, and in fact, most of the topics covered in this article are by-products of this function.

The benefits of higher-order functions: encapsulation behavior

With higher-order functions, we can not only assign functions as above, but also pass them as parameters when the function is called. This opens the door to the creation of a constantly dynamic code base on which complex behavior can be directly passed as parameters to reuse it.

Imagine working in a purely object-oriented environment where you want to extend the functionality of the class to accomplish the task. In this case, you might use inheritance by encapsulating the implementation logic in an abstract class and then extending it into a set of implementation classes. This is a perfect OOP behavior, and it works, we:

Create an abstract structure to encapsulate our reusable logic

Created a secondary construct

We reuse the original class and extend it

Now, what we want is reuse logic, and we can simply extract the reusable logic into a function and pass that function as an argument to any other function, which saves the process of creating a "template" because, we're just creating functions.

The following code shows how to reuse program logic in OOP.

/ / Encapsulated behavior encapsulation behavior stract class LogFormatter {format (msg) {return Date.now () +: ":" + msg}} / / reuse behavior class ConsoleLogger extends LogFormatter {log (msg) {console.log (this.format (msg))}} class FileLogger extends LogFormatter {log (msg) {writeToFileSync (this.logFile, this.format (msg))}}

The second example is to extract the logic into a function so that we can mix and match what we need to easily create it. You can continue to add more formatting and writing features, and then just mix them with a single line of code:

/ / generic behavior abstraction function format (msg) {return Date.now () + ":" + msg} function consoleWriter (msg) {console.log (msg)} function fileWriter (msg) {let logFile = "logfile.log" writeToFileSync (logFile, msg)} function logger (output, format) {return msg = > {output (format (msg)}} / / use it const consoleLogger = logger (consoleWriter, format) const fileLogger = logger (fileWriter, format) by combining functions

Both methods have advantages, and both are very effective, and no one is the best. This is just to show the flexibility of this approach, and we have the ability to use behaviors (that is, functions) as parameters as if they were basic types (such as integers or strings).

The benefits of higher-order functions: concise code

A good example of this benefit is the Array method, such as forEach,map,reduce, and so on. In non-functional programming languages such as C, iterating over and transforming array elements requires the use of for loops or some other loop structure. This requires us to write code in a specified way, that is, the process by which the requirement description loop occurs.

Let myArray = [1, let 2, 3, 4] let transformedArray = [] for (I = 0; I

< myArray.length; i++) { transformedArray.push(myArray[i] * 2) } 上面的代码主要做了: 声明一个新变量i,该变量将用作myArray的索引,其值的范围为0到myArray的长度 对于i的每个值,将myArray的值在i的位置相乘,并将其添加到transformedArray数组中。 这种方法很有效,而且相对容易理解,然而,这种逻辑的复杂性会随着项目的复杂程度上升而上升,认知负荷也会随之增加。但是,像下面这种方式就更容易阅读: const double = x =>

X * 2 myArray = [1 Magi 2 Jing 3 Jue 4]; let transformedArray = myArray.map (double)

This approach is easier to read than the first, and because the logic is hidden in two functions (map and double), you don't have to worry about understanding how they work. You can also hide the multiplication logic inside the function in the first example, but the traversal logic must exist, which adds some unnecessary reading obstacles.

Corey

Function Corialization is a technique that transforms a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function) and returns a new function that accepts the remaining parameters and returns the result. Let's look at an example:

Function adder (a, b) {return a + b} / / becomes const add10 = x = > adder (a, 10)

Now, if all you need to do is add 10 to a series of values, you can call add10 instead of calling adder with the same second argument every time. This example looks stupid, but it embodies the ideal of Corey.

You can think of Corification as an inheritance of functional programming, and then go back to the logger example in this way, and you'll get the following:

Function log (msg, msgPrefix, output) {output (msgPrefix + msg)} function consoleOutput (msg) {console.log (msg)} function fileOutput (msg) {let filename = "mylogs.log" writeFileSync (msg, filename)} const logger = msg = > log (msg, ">", consoleOutput); const fileLogger = msg = > log (msg, "::", fileOutput)

Log's function requires three parameters, and we introduced it into a dedicated version that requires only one parameter, because we have chosen the other two parameters.

Note that the log function is treated as an abstract class simply because in my example, I don't want to use it directly, but there is no limit to doing so, because it's just a normal function. If we are using a class, we will not be able to instantiate it directly.

Combination function

Function combination is the process of combining two or more functions to generate a new function. Grouping functions together is like fastening a series of pipes together to allow data to flow through.

In computer science, function combination is an act or mechanism that combines simple functions into more complex functions. Just like the usual function composition in mathematics, the result of each function is passed as the parameter of the next function, and the result of the last function is the result of the whole function.

This is the definition of function combination from Wikipedia, and the bold part is the key part. When using Corialization, there is no such limitation, and we can easily use the preset function parameters.

Code reuse sounds great, but it's hard to implement. If the business nature of the code is too specific, it is difficult to reuse it. For example, the time code is too general and simple, and few people use it. So we need to balance the two, a way to make smaller, reusable components that we can use as building blocks to build more complex functions.

In functional programming, functions are our building blocks. Each function has its own function, and then we combine the functions we need to complete our requirements, which is a bit like Lego's building blocks, which we call combined functions in programming.

Look at the following two functions:

Var add10 = function (value) {return value + 10;}; var mult5 = function (value) {return value * 5;}

The above is a bit lengthy, let's rewrite it with the arrow function:

Var add10 = value = > value + 10 bot var mult5 = value = > value * 5

Now we need a function to add 10 to the passed parameter and then multiply it by 5, as follows:

Now we need a function to add 10 to the passed parameter and then multiply it by 5, as follows:

Var mult5AfterAdd10 = value = > 5 * (value + 10)

Although this is a very simple example, I still don't want to write this function from scratch. First of all, a mistake may be made here, such as forgetting parentheses. Second, we already have a function add10 plus 10 and a function mult5 multiplied by 5, so here we are writing code that has been repeated.

Use the function add10,mult5 to ReFactor mult5AfterAdd10:

Var mult5AfterAdd10 = value = > mult5 (add10 (value))

We just use existing functions to create mult5AfterAdd10, but there is a better way.

In mathematics, f ∘ g is a combination of functions, called "f by g" or, more commonly, "f after g". So (f ∘ g) (x) is equivalent to f (g (x)) means that f is called after g is called.

In our example, we have mult5 ∘ add10 or "add10 after mult5", so the name of our function is mult5AfterAdd10. Since Javascript itself does not do function combinations, take a look at how Elm is written:

Add10 value = value + 10mult5 value = value * 5mult5AfterAdd10 value = (mult5

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