Functional programming

What it means: Functional programming is a development style and a specification that emphasizes the use of functions.

What is a Currying?

Converts a function that takes multiple arguments to a function that takes a single argument and returns a function that takes the rest of the arguments and returns the result. A Currified function can continue to return a new function until all of its arguments are exhausted, which are cached through the closure and executed when the currified chain reaches the end of the function.

Pure functions

A pure function is one that returns the same output for a given input. Return results without external interference.

// Error example
let x = 3;
let sum = (y) = >x+y;

console.log(sum(7)) // 10 The calculation result here is unpredictable, and the calculation result is affected by external interference.

// Correct example
let sum = x= >x+3;
console.log(sum(7))
Copy the code

Possibilities that can be assembled into complex tasks. Consistent with modular concept and single responsibility principle.

Currie,

basis

We are familiar with the sum function

function sum(x,y){
  return x+y
}
console.log(sum(1.2)) / / 3
Copy the code

Let’s take the above function and currize it

function sum(x,y){
  return x+y
}

function curry(fn){
  return function (x){
    return function (y){
      return fn(x,y)
		}
  }
}

let mySum = curry(sum)
console.log(mySum(2) (5)) / / 7
Copy the code

As verified above, Currie is the process of converting a multi-parameter function into a nested unary function.

Multiple arguments (recursive implementation of the Curry function)

function sum(x,y,z){
  return x+y+z
}

function curry (fn){
 const c = (. args) = >(args.length === fn.length)?    //fn.length is the number of parametersfn(... args):(. _args) = >c(... args,... _args)return c
}

let mySum = curry(sum)
console.log(mySum(2) (5) (3)) / / 10
console.log(mySum(2.5) (3)) / / 10
Copy the code

This approach is about as compact and minimal as you can get. First of all, we can determine that the core of curryization is to determine the number of parameters that are passed in and take all of them. Secondly, we need to know that fn.length is the number of parameters accepted by fn function, so the implementation method can be read as: continuously obtain the passed parameters recursively until the number of parameters obtained is equal to the number of fn parameters, and finally pass all obtained parameters to FN and return the execution result.

Parameters of reuse

// Implement a method to determine the data type
const checktype = function(type, value) {
    return Object.prototype.toString.call(value) === `[object ${type}] `;
}

checktype('Number'.2); // true
checktype('Number'.12); // true 
checktype('Number'.51); // true 
// The type 'Number' argument is passed each time

function curry(fn,type){
  return function (value){
    return fn(type, value)
  }
}

// Check the Number type
let isNumber = curry(checktype,'Number')
console.log(isNumber(2)) //true

// Check the String type
let isString = curry(checktype,'String')
console.log(isString('hello')) //true
Copy the code

Here is the realization of the reuse of parameters, such a realization for the subsequent extension call brought great convenience.

At this point we should be able to feel the power of the Currie function, by using it in conjunction with pure functions it can elegantly implement complex functions.

Composition

Requirement: Get the parity of all periods in a string

  • Get all periods
  • Statistical length
  • Judge parity
let str = "Hello, I'm Jack Bauer. I'm 12 years old and I'm from Class 5. I like to watch PLMM."

// 1. Get a period
let sentenceNum = str= >str.match(/. /g)

// 2. Count length
let getCount = arr= >arr.length

// 3
let oddOrEven = num= >num%2= = =0?'even number':'odd'


// combination: find the statistical length of the period and judge odd and even
let compose = (. fns) = >str= >fns.reduce((result,fn) = >fn(result),str)
const myfn = compose(sentenceNum,getCount,oddOrEven);
console.log(myfn(str)); / / odd
Copy the code

Pipe

Compose execution is right-to-left, and PIPE execution is left-to-right.

const pipe = (. fns) = >val= >fns.reduce((acc,fn) = >fn(acc),val);
Copy the code

Pipeline, combination trade-off: the biggest difference between pipeline and combination lies in the different execution sequence, different data flow, the purpose is similar, so there is no superior or inferior points.

The significance of composition and pipes To combine many small functions to achieve more complex logic.

reference

You must know JS Corrification

Deep dive into functional programming