JavaScript: look at functional programming

I. Introduction

In JavaScript, the function is a first class citizen, it could be like strings, numbers and other variables, used as the data used and modified var. It can be used as values ​​as arguments, and returns the result may be. JavaScript can say is that functional programming. ES6 new language features, arrows functions, extended operator greatly help developers using functional programming techniques to develop.

 // Define a function arrow 
 var Print = (Message) => the console.log (Message)

1, as a function of the value

 // the value of the function is used as 
 const Array = [ "XYQ" , Print] 
 the console.log (Array) // [ "XYQ", function] (2)

2, the function as an argument

 // a function as an argument 
 // define a function lg, it receives a logger function argument, the functions that will be performed lg logger function this parameter 
 // due to the incoming print function takes one parameter, the logger function execution the default passed in a string 
 const LG = Logger => Logger ( "the I Am XYQ" ) 
 LG (Print) // the I Am XYQ

3, as the return value of the function

 // the return value of the function as the 
 // given a function fcVale, it receives a logger function, and its return value of the new functions, new functions can pass 
 // a variable for printing. Finally, a function created with the function fcVale fc, and fc to pass function call string 
 // var fcVale = function (Logger) { 
 //      return (Message) => Logger (message.toUpperCase ()) 
 // } 
 const = = Logger fcVale> Message => Logger (message.toUpperCase ()) // higher order function, the function may be a function of the received parameters or other functions as a return value 
 const FC = fcVale (Print) 
 FC ( "I AM XYQ" ) // the I AM XYQ

 

Second, the style

In JavaScript development, for programming functions are divided into two styles, are imperative and declarative, part of functional programming is declarative. The so-called imperative is to pay more attention to the function to perform the process to achieve the goal rather than the result, that is light weight execution results. The declarative, by contrast, a description of the results far better than the execution procedures, functions, declarative easy to understand what its purpose is, but the specific implementation details were hidden. In JavaScript, the programming declarative function and its widely.

 // definition of a string variable 
 var UserString = "My IS XYQ the Name"

1, imperative

 @ Imperative: Traversal string, the string of spaces are underlined [replace all the developer must know in order to read the code is fast acting function is to replace the function] 
 var TEMP = ""
  for ( var I = 0; I < userString.length; I ++ ) {
     IF (UserString [I] === "" ) { 
         TEMP + = "_" 
    } the else { 
         TEMP + = UserString [I] 
    } 
 } 
 the console.log (TEMP) // My_Name_is_XYQ

2, declarative

 // declarative: using regular expressions, string replace all the spaces with an underscore [developers to see replace the basic know the purpose of the function is to replace function] 
 const user_string = userString.replace (/ / g , "_") 
 console.log (user_string) // My_Name_is_XYQ

 

Third, the concept of

Functional programming is a core function in JavaScript, it's the core concept of a total of four, namely, immutability, pure function, data conversion, higher-order functions and recursion.

1, immutability, said that in functional programming, the data can not change, they can never be modified to achieve the working mechanism is immutable copy of the original data editing, then Instead of using.

<Script type = "text / JavaScript">
   
// define a person object var person = { name: "XYQ" , Age: 25 , Sex: "MALE" } // Method 1: Method Obejct.assign copy mechanism, creating a blank object and copy the current object to the object on a blank, and then rewrite the target value var copyPerson = function (Person, name) { return Object.assign ({}, Person, {name: name}) // {as} a blank subject, person to copy the {}, rewriting name value } var newPerson = copyPerson (Person, "YPX" ) the console.log (newPerson.name) // YPX the console.log (Person. name) // XYQ, can see the original object is not changed @ Method two: copying by the operator expansion characteristics of the target const copyPerson2 = (Person, name) => ({ ... Person, name }) var copyPerson newPerson2 = (the Person, "YPX" ) console.log (newPerson2.name) // YPX console.log (person.name) // XYQ, you can see the original object does not change // ---------- -------------------------------------------------- --------------------- // // define an array object var persons = [ {name: "XYQ" }, {name: "YPX" } ] / /Method a: Array.concat manner using arrays in series array, generate a new object and add the copy of the original array, can not use this variable function Array.push const the addPerson = (name, persons) => persons. the concat ({name}) var newPersons the addPerson = ( "HXF" , persons) the console.log (newPersons) // [{name: "XYQ"}, {name: "YPX"}, {name: "HXF"}] (. 3) the console.log (persons) // [{name: "XYQ"}, {name: "YPX"}] (2), the array can be seen that the original has not changed @ way: method using extended operator characteristic The array copy const addPerson2 = (name, persons) => [... persons, {name}] var newPersons2 = addPerson2 ( "HXF" , persons) the console.log (newPersons2) // [{name: "XYQ" }, {name:"YPX"}, {name: "HXF"}] (3) the console.log (persons) // [{name: "XYQ"}, {name: "YPX"}] (2), the array can be seen that the original has not changed
</ script>

2, pure function, a return is dependent on the input parameters Results function, it needs to receive the at least one parameter and always returns a value or other function that uses the argument as immutable data use, without any modification.

Pure function characteristics: 
1, should receive at least one parameter function; 
2, or the function should return a value other functions; 
3, should not modify or affect the function of any parameters passed to it
<Script type = "text / JavaScript"> // define a person object var person = { 
      name: "XYQ" , 
      Age: 25 , 
      Sex: "MALE" 
  } // Create a pure function, the return value is generated according to the parameters preson a new person, it does not change the parameters person, a new person changed returned. 
  the updatePerson = Person = const> ({ 
      ... Person, 
      name: "YPX" , 
      Sex: "FEMALE" 
  }) // print var newPerson = the updatePerson (Person) 
  the console.log (newPerson) // {name: "YPX" , age: 25, sex: " feMale"}

  
  

  

  
  
  the console.log (person)     // {name: "XYQ", Age: 25, Sex: "MALE"}, the original object is not changed person
 
</ script>

3, data conversion, since the functional programming data immutability, it will to a data conversion to another data, using the conversion function generation copy of the state of conversion.

 // definition of a city array 
 const Cities = [ "BeiJing", "of BoJian", "ChongDu" ] 

 // Use the Array.join system function () array by connecting a string delimiter 
 var cityString = cities.join ( ", " ) 
 the console.log (cityString) // BeiJing, of BoJian, ChongDu 
 the console.log (Cities)      // [" BeiJing "," of BoJian "," ChongDu "] (. 5) 

 // use the system function Array.filter () for filter predicate, the predicate is always a function returns a Boolean value 
 // will visit each of the array elements, matching city beginning with C, if it returns true, then it is added to the new array 
 const newCities = cities.filter (city = > City [0] === "C" ) 
 the console.log (newCities) // [ "of BoJian", "ChongDu"] (2) 
 Console.    log(cities)    //[ "BeiJing", "ChongQing", "ChongDu"] (5) 

 // still use the system function Array.filter (), instead of Array.pop () and Array.splice () function to delete elements. Since the latter two methods is variable. 
 deleteCity = const (deletedCity, Cities) => cities.filter (City => City! ==     deletedCity) 
 const newCities2 = deleteCity ( "BeiJing" , Cities) 
 console.log (newCities2) // [ "ChongQing", "ChongDu" ] (. 4) 
 the console.log (Cities)      // [ "BeiJing", "of BoJian", "ChongDu"] (. 5) 

 // use the system function Array.map (), the parameter is a function, the function in the array can be accessed each element will be executed when 
 const = newCities3 cities.map (City => `$ {City} China`) 
 the console.log (newCities3) // ["
 the console.log (Cities) // [ "BeiJing", "of BoJian", "ChongDu"] (. 5) 

 // still Array.map system function (), she may also be constructed of any object, values, arrays, and other functions 
 / / 1, the array to a subject 
 the let objectCities = cities.map (City => ({cityName: City})) 
 the console.log (objectCities) // [{cityName: "BeiJing"}, {cityName: "of BoJian"}, cityName {: "ChongDu"}] (. 3) 
 the console.log (Cities) // [ "BeiJing", "of BoJian", "ChongDu"] (. 3) 

 // 2, modify the object elements 
 const updateCityName = (originCityName, cityName, Cities) => 
            (cities.map (City => (city.cityName === originCityName)? ({... City, cityName}):city))
 const newObjectCities = updateCityName("BeiJing","TianJin",objectCities)
 console.log(objectCities) //[{cityName: "BeiJing"}, {cityName: "ChongQing"}, {cityName: "ChongDu"}] (3)
 console.log(newObjectCities) //[{cityName: "TianJin"}, {cityName: "ChongQing"}, {cityName: "ChongDu"}] (3)

 // 3、将对象转数组(配合Object.key函数使用)
 //定义一个city对象
 const cityObject = {"BeiJing":"China","NewYork":"USA"}
 const cityObjects = Object.keys(cityObject).map(key =>
     ({cityName: key, country: cityObject[key]})
 )
 console.log(cityObject) //{BeiJing: "China", NewYork: "USA"}
 console.log(cityObjects)//[{cityName: "BeiJing", Country: "China"}, {cityName: "NewYork", Country: "USA"}] (2) 

 // system function Array.reduce () and rArray.reduceRight () may be used the switch array to an arbitrary value, such as numbers, strings, Boolean values, and even the object function 
 // Array.reduce () function, the processing starts from the head array elements; Array.reduceRight () function, the processing starts from the end of the array element 
 / / most value 
 const the nums = [10,5,30,24,78,60,100 ] 
 const max = nums.reduce ((max, NUM) => (NUM> max)? NUM: max) 
 const min = nums.reduce ((min, NUM) => (NUM <min)? NUM: min) 
 the console.log (max) // 100 
 the console.log (min) // . 5 

 // deduplication, items for the new empty array 
 const names = [ "XYQ", "YPX" , "XXF", "XYQ","XYQ" , "XXF", "XYQ","XYQ"]
 const deletedNames = names.reduce((items, name)=> items.indexOf(name) !== -1 ? items : [...items,name], [])
 console.log(names) //["XYQ", "YPX", "XXF", "XYQ", "XYQ"] (5)
 console.log(deletedNames) //["XYQ", "YPX", "XXF"] (3)

4, higher-order functions, can be a function of other operating functions, they can be used as parameter transfer function may be a function return, or both of. Currying is a typical application.

 // define the higher-order functions, to function as a parameter 
 const Printer = () => console.log ( "--- Printer ---" ) 
 const Logger   = () => console.log ( "--- Logger - - " ) 
 const Show ? = (selectPrint, Printer, Logger) => (selectPrint) Printer (): Logger () 

 // call the higher-order function 
 Show ( to true , Printer, Logger)   // --- Printer --- 
 Show ( to false , Printer, Logger) // --- --- Logger 
        
 // definition of high order function as the function return value 
 const = log (Message) => (() => the console.log (Message)) 
 const logFunction log = ( "the I Am XYQ" ) 

 // calls the higher-order functions 
 logFunction ()//I Am XYQ

5, recursion, which is a function created by the user that calls itself a technical solution, encountered in the development cycle, extremely streamlined by recursively can shorten the amount of code, it is an advantage alternative.

 // define a reverse traversal function 
 const the countDown = (Number, log) => { 
      log (Number) 
      return (Number> 0) the countDown (. 1-Number? , Log): Number 
 } 

 // the function is called 
 const log = ( Number) => the console.log (Number) 
 the countDown ( . 5, log) // . 5. 4. 3. 1 0 2

 

 Four , chain

Functional programming is to split the service logic into a specific small-sized simple purely functional, easy focusing function, and ultimately, the synthesis of these small developers will function together can be called by a series or parallel manner. The synthesis process is actually chained calls. Such as the application object before the introduction of Promise.

 //使用系统函数replace实现链式调用
 const formmater = "hh:mm:ss tt"
 const currentTime = formmater.replace("hh", "22").replace("mm","07").replace("ss","00").replace("tt","PM")
 console.log(currentTime) //22:07:00 PM

 

Guess you like

Origin www.cnblogs.com/XYQ-208910/p/11965612.html