Beginner's Guide, functional javascript: local apply

Source: Internet
Author: User
Tags naming convention readable

Local or local applications are functional techniques that may sound confusing to those familiar with the way traditional JavaScript code is written, but it does make your JavaScript code more readable if applied properly.

Greater readability, greater flexibility

One of the advantages of functional JavaScript code is that its code is shorter and stricter, it can be used with a minimum number of lines and less repetitive code, and, of course, it sometimes sacrifices readability. And before you know how this functional programming works, code written in this way makes it harder to read and more difficult to understand!

If you've encountered the term local, but never know what it means, then you can be forgiven because they think it's a strange technique you don't need to worry about. But a partial apply is actually a very simple concept that solves some of the familiar problems we have when dealing with function parameters, and opens up a series of flexible options for developers.

What is a partial apply?

In short, a local application is a way for a constructor to allow you to apply a function parameter locally, which means that you can pass all the arguments that the function expects and get the result, or pass a subset of the parameter and return a function that waits for the remaining arguments. It's really that simple.

Local apply is a language element similar to Haskell and Scala around functional concepts, JavaScript has functional functions, but local formatting is not the default way of creation (at least in the current version of the language), but we still know some functional tricks, And we can also make the local application work for us in JavaScript.

To understand how the local application works, let's use the familiar syntax in JavaScript to create the first function that we want to have local functionality. For example: Let's imagine a function that greets others by name, and we all know how to create a simple greeting function with a name and greeting, and output a log of the greeting with the name in the console:

var greet = function (greeting,name) {Console.log (greeting+ "," +name ");};        Greet ("Hello", "Heidi"); "Hello,heidi"

This function requires that name and greeting be passed in as arguments so that it works, but we can override this function by using a simple nested local application, so that the underlying function only needs to greeting one argument. And the function returns another function with the name of the person we want to greet.

Our first partial apply

var greetcurried = function (greeting) {return function (name) {Console.log (greeting+ "," +name "); };};

We've created a new function that can have any kind of greeting by this tiny tweak, and pass the name of the person we want to greet to the new function:

var Greethello = greetcurried ("Hello"); Greethello ("Heidi");   "Hello,heidi" Greethello ("Eddie"); "Hello,eddie"

We can also call the original locally applied function directly, just pass the parameters in each set of separate parentheses to ensure the correctness of each parameter:

Greetcurried ("Hi There") ("Howard"); "Hi There,howard"

Why not try it in your browser?

Here is the JavaScript code:

This is the effect of the browser console:

Apply all the things locally

The cool thing is that since we've learned how to use this method to manipulate parameters to modify our traditional functions, we can also use this method to handle more of the parameters we want:

var greetdeeplycurried = function (greeting) {return function (separator) {return function (emphasis) {R            Eturn function (name) {Console.log (greeting+separator+name+emphasis);        };    }; };};

Our function has four parameters and two parameters with the same flexibility, no matter how deep the nesting, we can create a new custom function to greet as many of the people we choose to fit our purpose.

var greetawkwardly = greetdeeplycurried ("Hello") ("...") ("?");  greetawkwardly ("Heidi"); "Hello ... Heidi? "  greetawkwardly ("Eddie"); "Hello ... "Eddie?"

More importantly, when we create a custom variable in the original local function, we can pass as many arguments as possible, creating a number that can get the appropriate additional parameters, each of which is passed in its own parentheses (that is, the scope):

var SayHello = greetdeeplycurried ("Hello") (","); SayHello (".")  ("Heidi"); "Hello, Heidi." SayHello (".")  ("Eddie"); "Hello, Eddie."

And we can easily define dependent variables:

var Askhello = SayHello ("?");  Askhello ("Heidi"); "Hello, Heidi?"  Askhello ("Eddie"); "Hello, Eddie?"

here is the JavaScript code:

This is the effect in the browser:

Apply traditional functions locally

You can see how powerful this approach is, especially if you need to create a lot of very detailed custom functions. The only problem is grammar. When you create a local function, you need to return the nested function and call them with a new function that requires multiple parentheses, each with its own independent argument, which can be confusing.

One way to solve this problem is to create a quick, dirty (dirty, mostly global variable that pollutes the global environment) that can get to a local constructor that does not have any nested returned function names (in combination with the following code description: Create a global local function, Named Curryit, get uncurried as a parameter,uncurried is an existing function without any nested returns ). A local application function needs to take out its argument list and use the list of parameters taken out to return a locally applied version of the initial function:

var curryit = function (uncurried) {var parameters = Array.prototype.slice.call (arguments,1);    return function () {return uncurried.apply (This,parameters.concat (Array.prototype.slice.call (arguments,0))); };};

Using this, we pass a function name with any number of arguments (as much as we want in advance), and we get a function that waits for the remaining arguments:

var greeter = function (greeting, separator, emphasis, name) {Console.log (greeting + separator + name + emphasis);}; var Greethello = Curryit (greeter, "Hello", ",", "."); Greethello ("Heidi"); "Hello, Heidi." Greethello ("Eddie"); "Hello, Eddie."

As before, when we create a derived function from the original local function, we do not limit the number of arguments we want:

var Greetgoodbye = Curryit (greeter, "Goodbye", ","); Greetgoodbye (".", "Joe"); "Goodbye, Joe."

here is the JavaScript code:

This is the effect in the browser:

Start thinking about local apply

Some of the small local functions we have mentioned may not be able to handle the boundary conditions used, such as missing or optional parameters, but it is a reasonable way of working as long as we maintain strict syntax when passing parameters.

Some functional JavaScript libraries (such as RAMDA) have more flexible local functions that do not limit the required parameters , and allow you to pass parameters individually or collectively, creating custom locally applied variables (i.e.:

var curryit = function (uncurried) {...};

)。 This can be a good way if you want to use the extended local application.

Regardless of how you choose to add a local application to your programming, choose to use nested parentheses or you will prefer to include a more robust hosting function, and think of a consistent naming convention for your local function to make your code more readable. Each derived variable of a function (that is, a variable that exceeds the number of arguments given by the function) should have a clear name that describes its behavior and the desired parameter properties.

Parameter order

One important thing is that you have to remember the order of the parameters in the local application, and using the method we describe, you obviously need a parameter that can be replaced individually (i.e., in order).

Considering the order of the parameters in advance will make it easier for you to plan for the local application and apply it to your work. And it would be a good practice to consider which parameters in your order parameter list might be least likely to change when you design a function.

Conclusion

Local application is a very useful technique in functional JavaScript. It allows you to generate a very small library, easily configure consistent functions, can be used quickly, and can be understood when others are reading your code. Adding local applications to your programming practice will prompt you to use some of the application functionality in your code, avoiding potential duplication, and allowing you to have a better habit of writing and processing function parameters.


Beginner's Guide, functional javascript: local apply

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.