JavaScript functional programming

Source: Internet
Author: User

JavaScript functional programming

This article records some of the things I have learned in functional learning, deepen my memory and record it, so that I can easily review it later.

I recently saw the book JavaScript functional programming, which was finalized at the time of pre-sale. The main purpose is to do not understand functional programming. In the process of learning, I have always heard people around me say that process-oriented programming and object-oriented programming, and there are very few functional styles. In order not to lag behind other students, I want to share and record the knowledge I have learned by taking notes.

Js and functional programming

The book uses a simple sentence to answer what is functional programming:

Function programming converts a value to an abstract unit by using a function and then builds a software system.
I think some of you may have read this sentence, but I still don't know what functional programming is, and why should I use functional programming. Many examples later use Underscore.

Abstract unit with Function

Abstract methods are functions that hide details. For example, in a book, a function is used to detect and output age values (mainly reports about errors and warnings ):

function parseAge(age) {  if (!_.isString(age))    throw new Error("Expecting a string");  var a;  console.log("Attempting to parse an age");  a = parseInt(age, 10);  if (_.isNaN(a)) {    console.log(["Could not parse age: "].join());    a = 0;  }  return a;}

The above function determines whether we enter an age and must be in the string format. Then run this function:

parseAge("42"); //=> 42parseAge(42); //=> Error:Expecting a stringparseAge("hhhh"); //=> 0

The preceding parseAge function works normally. If we want to modify the rendering mode of Output Error = information and warning, we need to modify the corresponding code lines and the output mode elsewhere. The method given in the book is to abstract them into different functions:

function fail(thing) {  throw new Error(thing);}function warn(thing) {  console.log(["WARNING:", thing].join(''));}function note(thing) {  console.log(["NOTE:", thing].join(''));}

Then we use the above function to reconstruct the parseAge function.

funciton parseAge(age) {  if (!_.isString(age))    fail("Expecting a string");  var a;  note("Attempting to parse an age");  a = parseInt(age, 10);  if (_.isNaN(a)) {    warn(["Could not parse age:", age].join(""));    a = 0;  }  return a;}

Put the reported error code in different functions, and the reconstructed parseAge does not change much. However, the difference is that the ideas for reporting errors, messages, and warnings have been abstracted. The report results of errors, messages, and warnings are completely modified.

In doing so, because the behavior is included in a single function, the function can be replaced by a new function that provides similar behavior, or directly by a completely different behavior.

Encapsulation and concealment

This title is easy to understand. For example. As we often use iife to avoid global pollution, this is a good example of encapsulation and concealment. By using iife to conceal some of the variables and methods you write, the goal is not to pollute the global environment. This also uses closures to conceal data.

Because closures are also a function. It has a great relationship with functional programming. But do not forget the object-oriented encapsulation that we learned before. After all, the two cannot be better. However, it is not a bad thing to master. An old saying goes: depending on your needs.

Unit of action with Function

Hiding data and behavior (which is usually not convenient for quick modification) is just a way of talking about functions as abstract units. Another method is to provide a simple storage method and an offline discrete unit that transmits basic behavior.

A small chestnut in the book, using js syntax to index a value in the array:

var arr = ['a', 'b', 'c'];arr[1] //=> b

Although a value in the above index array is very simple, there is no way to get this behavior and use it as needed without putting it in the function. Write a simple function nth to index a value in the array:

function nth(a, index) {  return a[index];}

Run:

Nth (arr, 1); // => B
It runs successfully, but if an empty object is input, an error is returned. Therefore, if we want to implement function abstraction around nth, we may design the following statement: nth returns a valid yuanshu stored in the data type that allows index access. The key to this statement lies in the concept of index data types. You may need a function to determine the type:

function isIndexed(data) {  return _.isArray(data) || _.isString(data);}

Then we continue to improve the nth function. The isIndexed function is an abstraction that determines whether a data is a string or an array.

function nth(a, index) {  if (!_.isNumber(index))     fail("Expected a number as the index");  if (!isIndexed(a))    fail("Not supported on non-indexed type");  if ((index < 0) || (index > a.length - 1))    fail("Index value is out of bounds");  return a[index];}

The same method is used to extract objects from the index to construct nth function abstraction. You can also build a second abstraction in the same way:

function second(a) {  return nth(a, 1);}

The second function allows the correct use of the nth function in a different but related case:

Second (arr); // => B
Through the chestnuts above, you will know. We can abstract every step into a function and every parameter. Although this write process defines many functions. However, this makes it easier to understand the functions and processes of each item.

Data abstraction

The object prototype model of JavaScript is a rich and basic data solution.
Because js does not have a class, there are many methods for simulating classes, and the class keyword also appears on es6. Although the class has many advantages, the data requirements of js applications in many cases are much simpler.

A rational argument for class-based object systems is to achieve the historical use of user interfaces.
Objects and arrays in js can satisfy our data operations, and Underscore also focuses on how to process arrays and objects.

The simplicity of implementation and use is the purpose of using the core data structure of js for data modeling. This does not mean that object-oriented or class-based methods are completely useless. The collection-centered function method is more suitable for processing human-related data, while the object-oriented method is most suitable for human simulation.

Initial js function test

Before starting functional programming, You need to define two common and useful functions:

function existy(x) {  return x != null}function truthy(x) {  return (x !== false) && existy(x);}

The existy function is designed to define the existence of a thing before it exists. There are two values in js that can indicate that null and undefined do not exist.
The truthy function is used to determine whether an object should be considered a synonym of true.

We can use these two functions in many places. In fact, the functional concept comes from their usage. Some may already be familiar with map forEach and other methods in js implementation. Underscroe also provides many similar methods, which may be the reason for choosing Underscroe to help you learn functional programming.

To put it simply:

A definition of an abstract function with "existence.
An abstract function defined on the basis of an existing function.
Use other functions to use the above two functions to implement more actions.

Acceleration

After learning about functional programming. Maybe you think this function programming is not very slow? For example, to obtain the array index, do you need to define a function to obtain it? Directly Using arr [index] Is Definitely faster than those functions.

Var arr = [1, 2, 3, 4, 5]; // The fastest for (var I = 0; I <arr. length; I ++) {console. log (arr [I]);} // slow _. each (arr, function (val, index) {console. log (index );});

However, we may not take this into consideration when writing code. Maybe the use of functions is indeed slower than that of native. But in most cases, I don't care much about the time, and now there is a powerful v8 engine. In most cases, he can efficiently compile and execute our js Code. Therefore, we do not need to consider the computing speed before writing the correct code.

If I choose it, I may pay more attention to the Code style. Which of the following statements can be used for the comfort of writing? Of course, it is also necessary to ensure the basic computing speed, so as not to be too slow. The code that looks comfortable may feel more fulfilled than the code that runs fast.

Summary

After reading the first chapter, you can also summarize js functional programming. The following is a summary of the reference:

Determine the abstraction and construct a function for it.
Use existing functions to construct more complex abstractions.
Construct more complex abstraction by passing existing functions to other functions.
Building abstraction alone is not enough. It would be better if powerful data abstraction can be combined to implement functional programming.

The subsequent sections will be shared with you slowly.

Related Article

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.