


An in-depth analysis of function currying in JavaScript_javascript skills
The origin of curry is the name of mathematician Haskell Curry (the programming language Haskell is also named after him).
Currying is usually also called partial evaluation. Its meaning is to pass parameters to a function step by step. After each parameter is passed, the parameters are partially applied and a more specific function is returned to accept the remaining parameters. This can be nested multiple levels in the middle. The function accepts some parameters until the final result is returned.
Therefore, the process of currying is a process of gradually passing parameters, gradually narrowing the applicable scope of the function, and gradually solving the problem.
Currying a summation function
According to the step-by-step evaluation, let’s look at a simple example
var concat3Words = function (a, b, c) { return a+b+c; }; var concat3WordsCurrying = function(a) { return function (b) { return function (c) { return a+b+c; }; }; }; console.log(concat3Words("foo ","bar ","baza")); // foo bar baza console.log(concat3WordsCurrying("foo ")); // [Function] console.log(concat3WordsCurrying("foo ")("bar ")("baza")); // foo bar baza
As you can see, concat3WordsCurrying("foo ") is a Function. Each call returns a new function, which accepts another call and then returns a new function until the final result is returned. Distribution solution, Progress step by step. (PS: The characteristics of closure are used here)
So now we go one step further. If we require more than 3 parameters to be passed, we can pass as many parameters as we want. When no parameters are passed, the result is output?
First let’s do a common implementation:
var add = function(items){ return items.reduce(function(a,b){ return a+b }); }; console.log(add([1,2,3,4]));
But if it is required to multiply each number by 10 and then add it up, then:
var add = function (items,multi) { return items.map(function (item) { return item*multi; }).reduce(function (a, b) { return a + b }); }; console.log(add([1, 2, 3, 4],10));
Fortunately, there are map and reduce functions. If we follow this model and now add 1 to each item and then summarize it, then we need to replace the function in map.
Let’s take a look at the currying implementation:
var adder = function () { var _args = []; return function () { if (arguments.length === 0) { return _args.reduce(function (a, b) { return a + b; }); } [].push.apply(_args, [].slice.call(arguments)); return arguments.callee; } }; var sum = adder(); console.log(sum); // Function sum(100,200)(300); // 调用形式灵活,一次调用可输入一个或者多个参数,并且支持链式调用 sum(400); console.log(sum()); // 1000 (加总计算)
The above adder is a curried function. It returns a new function. The new function can accept new parameters in batches and delay the calculation until the last time.
Universal currying function
The more typical currying will encapsulate the last calculation into a function, and then pass this function as a parameter to the currying function, which is clear and flexible.
For example, if each item is multiplied by 10, we can pass the processing function as a parameter:
var currying = function (fn) { var _args = []; return function () { if (arguments.length === 0) { return fn.apply(this, _args); } Array.prototype.push.apply(_args, [].slice.call(arguments)); return arguments.callee; } }; var multi=function () { var total = 0; for (var i = 0, c; c = arguments[i++];) { total += c; } return total; }; var sum = currying(multi); sum(100,200)(300); sum(400); console.log(sum()); // 1000 (空白调用时才真正计算)
In this way, sum = currying(multi), the call is very clear, and the use effect is also brilliant. For example, if you want to accumulate multiple values, you can use multiple values as parameters sum(1,2,3), which can also be supported Chained calls, sum(1)(2)(3)
The basics of currying
The above code is actually a high-order function. A high-order function refers to a function that operates on functions. It receives one or more functions as parameters and returns a new function. In addition, it also relies on the characteristics of closures to save the parameters entered in the intermediate process. That is:
Functions can be passed as parameters
Functions can be used as function return values
Closure
The role of currying
Delayed calculation. The above example is relatively easy to explain.
Parameter reuse. When the same function is called multiple times and the parameters passed are mostly the same, then the function may be a good candidate for currying.
Dynamicly create functions. This can be done by dynamically generating a new function to handle the subsequent business after partially calculating the results, thus eliminating repeated calculations. Or you can dynamically create a new function by partially applying a subset of the parameters to be passed into the calling function to the function. This new function saves the parameters that are passed in repeatedly (you don’t have to pass them in every time in the future). For example, the event browser adds a helper method for events:
var addEvent = function(el, type, fn, capture) { if (window.addEventListener) { el.addEventListener(type, function(e) { fn.call(el, e); }, capture); } else if (window.attachEvent) { el.attachEvent("on" + type, function(e) { fn.call(el, e); }); } };
Every time you add event processing, you need to execute if...else.... In fact, only one judgment is needed in a browser. A new function is dynamically generated based on the result of one judgment, so there is no need to do so in the future. Recalculate.
var addEvent = (function(){ if (window.addEventListener) { return function(el, sType, fn, capture) { el.addEventListener(sType, function(e) { fn.call(el, e); }, (capture)); }; } else if (window.attachEvent) { return function(el, sType, fn, capture) { el.attachEvent("on" + sType, function(e) { fn.call(el, e); }); }; } })();
In this example, after the first if...else... judgment, part of the calculation is completed, and a new function is dynamically created to process the parameters passed in later. This is a typical currying.
Function.prototype.bind method is also curried application
Different from the direct execution of the call/apply method, the bind method sets the first parameter as the context of function execution, and the other parameters are passed to the calling method in turn (the body of the function itself is not executed and can be regarded as delayed execution), and Dynamic creation returns a new function, which conforms to the characteristics of currying.
var foo = {x: 888}; var bar = function () { console.log(this.x); }.bind(foo); // 绑定 bar(); // 888
The following is a simulation of the bind function. testBind creates and returns a new function. In the new function, the function that actually performs the business is bound to the context passed in as the actual parameter, and the execution is delayed.
Function.prototype.testBind = function (scope) { var fn = this; //// this 指向的是调用 testBind 方法的一个函数, return function () { return fn.apply(scope); } }; var testBindBar = bar.testBind(foo); // 绑定 foo,延迟执行 console.log(testBindBar); // Function (可见,bind之后返回的是一个延迟执行的新函数) testBindBar(); // 888
Here we should pay attention to the understanding of this in prototype.
The above article is an in-depth analysis of function currying in JavaScript. This is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.
