_javascript skills in "JavaScript functional Programming"

Source: Internet
Author: User
Tags function definition

This article records people in the learning function to understand some things, deepen the memory and record down, convenient review.

In the recent see "JavaScript function Programming" This book when the pre-sale was set down. The main purpose is for individuals to currently or not understand what is functional programming. In the course of their own learning has been heard around people say process-oriented programming and object-oriented programming, and the function is very small. In order to not lag behind the footsteps of other students, so want to write notes to share and record their reading of the knowledge learned.

JS and functional programming

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

Functional programming uses functions to convert values to abstract units, which are then used to build software systems.
I think someone must have read the sentence or not. What is functional programming and why use functional programming. Many of the following examples are used in underscore.

To abstract a function as a unit

An abstract method is a function that hides the details. For example in a book, a function that detects an output age value (mainly a report on errors and warnings):

function Parseage (age) {
  if (!_.isstring)
    throw new Error ("expecting a string");
  var A;
  Console.log ("Attempting to parse");

  A = parseint (age, ten);
  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 a string form. And then we're going to run this function:

Parseage ("42"); =>
Parseage (a);//=> error:expecting A string
parseage ("HHhH");//=> 0

The above Parseage function works fine without any problems. If we want to modify the output error = the way information and warnings are rendered, we need to modify the corresponding line of code and the output pattern elsewhere. The method given in the book is achieved by abstracting them into different functions:

function fail (thing) {
  throw new Error (thing);
}

function warn (thing) {
  console.log (["WARNING:", Thing].join ("));
}

function Note (thing) {
  console.log ([??], Thing].join ("));
}

Then you use the above function to refactor the Parseage function.

Funciton Parseage (age) {
  if (!_.isstring)
    fail ("expecting a string");
  var A;

  Note ("Attempting to parse a age");
  A = parseint (age, ten);

  if (_.isnan (a)) {
    warn (["Could not parse Age:", Age].join (""));
    A = 0;
  }

  return A;
}

The code that reports the error is placed in a different function, and the parseage and previous changes are not much changed after the refactoring. But the difference is that now the idea of reporting errors, messages, and warnings has been abstracted. The results of errors, messages, and warnings were also completely modified.

This is because the behavior is contained in a single function, so the function can be replaced by a new function that can provide a similar behavior, or be directly replaced by a completely different behavior.

Encapsulation and concealment

The title is easy to understand, for instance. 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 their written variables and methods, the goal is not to pollute the global environment. This is also a way of using closures to conceal data.

Because closures are also a function. And now in learning functional programming has a great relationship. But also do not forget the previous study of the object-oriented package, after all, the two can not say who is better. But it is not a bad thing to have mastered it. An old saying: look at demand.

Act as a function unit

hiding data and behavior (often inconvenient for quick modifications) is just a way to talk about functions as abstract units. Another way is to provide an off-line hash unit that simply stores the way and passes basic behavior.

A little chestnut in the book, by using the JS syntax to index a value in an array:

var arr = [' A ', ' B ', ' C '];
ARR[1]//=> b

Although one of the values in the index array above is simple, there is no way to get this behavior and use it as needed, without putting it into a function. Write a simple function nth that is used to index a value in an array:

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

Then run:

Nth (arr, 1); => b
Run successfully, but if you pass in an empty object, you will get an error. Therefore, if you want to implement function abstraction around nth, we might design the following statement: Nth returns a valid yuan stored in a data type that allows index access. The key to this statement is the concept of the type of index data. You might need a function to determine the type:

function isindexed (data) {return
  _.isarray (data) | | _.isstring (data);
}

Then continue to refine the nth function. The Isindexed function is an abstraction that provides a method of determining whether a data is a string or an array.

function nth (A, index) {
  if (!_.isnumber (index)) 
    fail ("expected a number as the");
  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];
}

As with the way the nth function abstraction is constructed from the Index object, a second abstraction can be constructed in the same way:

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

Function Second allows the correct use of the nth function in a different but relevant case:

Second (arr); => b
Through the chestnuts above, you know. We can abstract each step into a function and abstract each parameter. Although this writing feeling defines a number of functions. However, this makes it easier to understand the features and processes of each item.

Data abstraction

The object prototype model of JavaScript is a rich and basic data scheme.
Because JS has no class reason, there are many ways to simulate the class, and on the ES6 also appeared the Class keyword. Although the class has many advantages, but many times the JS application of the data requirements in the currency is much simpler.

A rational argument for a class based object system is to implement the historical use of the user interface.
The objects and arrays in JS have been able to satisfy our data manipulation, and underscore is also focused on how to handle arrays and objects.

The simplicity of implementation and use is the purpose of data modeling using JS's core data structure. This is not to say that object-oriented or class based methods are completely useless. It is more suitable to deal with people-related data, while the Object-oriented method is most suitable for simulating people.

JS Function Type Preliminary examination

Before you begin functional programming, you need to define two commonly used 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 things before. In JS, there are two values that can indicate that they do not exist: null and undefined.
The Truthy function is used to determine whether an object should be considered a synonym for true.

We can use these two functions in many places, but the functional concept comes from their use. Some students may already be familiar with many of the JS implementation of the map foreach and other methods. And Underscroe also provides a number of similar methods, which may be the reason to choose Underscroe to assist in learning functional programming.

The simple saying is:

A definition of an abstract function for "being".
An abstract function definition of "true" based on the existence function.
Use the above two functions with other functions to achieve more behavior.

Accelerated

I've probably learned about functional programming. You might think that this functional programming is not very slow? For example, to get an array index, is it necessary to define a function to get it specifically? Directly with Arr[index] is definitely faster than those functions.

var arr = [1, 2, 3, 4, 5];

Fastest for
(var i = 0; i < arr.length i++) {
  console.log (arr[i]);
}

Slower
_.each (arr, function (val, index) {
  console.log (index);
});

But we might not think about it as much while writing code, and perhaps using a function is actually slower than native. But in most cases it doesn't care about the time, and now there is a strong V8 engine, and in most cases he can compile and execute our JS code efficiently. So we don't need to think about the speed before we write the right code.

If I were to choose, I might be more concerned with the style of the code. The way to write the comfortable look comfortable on the use of which, of course, to ensure the basic speed of operation, to not slow outrageous. Looking at the comfortable code may be more fulfilling than running faster code.

Summarize

After reading the first chapter is also a summary of the function of JS programming. The following is a summary of the book:

Determine the abstraction and build the function for it.
Use existing functions to build more complex abstractions.
Build more complex abstractions by passing existing functions to other functions.
Building abstractions alone is not enough, and it would be better to combine powerful data abstractions to achieve functional programming.

Later chapters of the book will be slowly share to everyone, please pay attention to.

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.