This is the third day of my participation in Gwen Challenge

Why learn functional programming

Functional programming is a very old concept, long before the birth of the first computer, the history of functional programming. Why learn functional programming now?

  • Functional programming is getting more attention with the popularity of React
  • Vue 3 also began to embrace functional programming
  • Functional programming can discard this
  • Better use of Tree Shaking to filter out useless code during packaging
  • Convenient for testing and parallel processing
  • There are many libraries to help us with functional development: Lodash, underscore, Ramda

What is functional programming

Functional Programming (FP), FP is one of the Programming paradigms, we often hear of procedural oriented Programming paradigms

  • Programming, object-oriented programming.
  • The way of thinking of object-oriented programming: abstract the things in the real world into classes and objects in the program world, and demonstrate the connection of things and events through encapsulation, inheritance and polymorphism
  • The way of thinking about functional programming: Abstracting things and their relationships from the real world to the program world
    • The essence of the program: according to the input through some operation to obtain the corresponding output, the process of program development will involve a lot of input and output functions X -> F (connection, mapping) -> y, y= F (x) function in functional programming refers not to the function (method) in the program, but the function in mathematics, namely mapping relationship, for example: Y is equal to sine of x, the relationship between x and y
    • The same input always produces the same output (pure function)
    • Functional programming is used to describe mappings between data (functions)
// Non-functional
let num1 = 2
let num2 = 3
let sum = num1 + num2
console.log(sum)
/ / function type
function add (n1, n2) {
return n1 + n2
}
let sum = add(2.3)
console.log(sum)
Copy the code

The function is a first-class citizen

MDN First-class Function

  • Functions can be stored in variables
  • Function as argument
  • Function as the return value

In JavaScript, a Function is just an ordinary object (via new Function()), we can store the Function in a variable/array, and it can be used as an argument and return value to another Function, We can even construct a new Function while the program is running by using new Function(‘alert(1)’).

  • Assign a function to a variable
// Assign a function to a variable
let fn = function () {
    console.log('Hello First-class Function')
}
fn()
// An example
const BlogController = {
    index (posts) { return Views.index(posts) },
    show (post) { return Views.show(post) },
    create (attrs) { return Db.create(attrs) },
    update (post, attrs) { return Db.update(post, attrs) },
    destroy (post) { return Db.destroy(post) }
}
/ / optimization
const BlogController = {
    index: Views.index,
    show: Views.show,
    create: Db.create,
    update: Db.update,
    destroy: Db.destroy
}
Copy the code
  • The function is first-class citizen is the basis of higher order function, Currization, etc.

Higher-order functions

What is a higher-order function

  • Higher-order functions
    • You can pass a function as an argument to another function
    • You can treat a function as the return result of another function
  • Function as argument
// forEach
function forEach (array, fn) {
    for (let i = 0; i < array.length; i++) {
        fn(array[i])
    }
}
// filter
function filter (array, fn) {
    let results = []
    for (let i = 0; i < array.length; i++) {
        if (fn(array[i])) {
        results.push(array[i])
        }
    }
    return results
}
Copy the code
  • Function as the return value
function makeFn () {
    let msg = 'Hello function'
    return function () {
        console.log(msg)
    }
}
const fn = makeFn()
fn()
Copy the code
// once
function once (fn) {
let done = false
return function () {
    if(! done) { done =true
        return fn.apply(this.arguments)}}let pay = once(function (money) {
    console.log(` pay:${money} RMB`)})// Will only be paid once
pay(15)
pay(15)
pay(15)
Copy the code

The meaning of using higher-order functions

  • Abstraction can help us mask the details and focus only on our goals
  • Higher-order functions are used to abstract general problems
// Process oriented approach
let array = [1.2.3.4]
for (let i = 0; i < array.length; i++) {
    console.log(array[i])
}
// Higher-order higher-order functions
let array = [1.2.3.4]
forEach(array, item= > {
    console.log(item)
})
let r = filter(array, item= > {
    return item % 2= = =0
})
Copy the code

Higher-order functions are commonly used

  • forEach
  • map
  • filter
  • every
  • some
  • find/findIndex
  • reduce
  • sort
const map = (array, fn) = > {
    let results = []
    for (const value of array) {
        results.push(fn(value))
    }
    return results
}
const every = (array, fn) = > {
let result = true
    for (const value of array) {
        result = fn(value)
        if(! result) {break}}return result
}
const some = (array, fn) = > {
let result = false
for (const value of array) {
    result = fn(value)
        if (result) {
            break}}return result
}
Copy the code