This is the fourth day of my participation in Gwen Challenge

closure

  • Closure: A Closure is formed by binding a function with references to its surrounding state (lexical context).
    • You can call an inner function of a function from another scope and access members of that function’s scope
// function as 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(5)
pay(5)
Copy the code
  • The essence of closures: functions are placed on an execution stack at execution time and removed from the stack when the function completes execution, but the scoped members on the heap cannot be freed because they are referenced externally, so the inner function can still access the member closure cases of the external function
  • Closure case
// Generates a function that computes the power of a number
function makePower (power) {
    return function (x) {
        return Math.pow(x, power)
    }
}
let power2 = makePower(2)
let power3 = makePower(3)
console.log(power2(4))
console.log(power3(4))
Copy the code
// The first number is base salary, and the second number is merit pay
function makeSalary (x) {
    return function (y) {
        return x + y
    }
}
let salaryLevel1 = makeSalary(1500)
let salaryLevel2 = makeSalary(2500)
console.log(salaryLevel1(2000))
console.log(salaryLevel1(3000))
Copy the code

Pure functions

Pure function concept

  • Pure functions: The same input always yields the same output without any observable side effects
    • A pure function is like a function in mathematics, y = f(x).

  • Lodash is a library of pure functions that provides methods for operating on arrays, numbers, objects, strings, functions, and more
  • Arrays of slice and splice are pure and impure functions, respectively
    • Slice returns the specified portion of the array without altering the original array
    • Splice operates on an array and returns that array, changing the original array
let numbers = [1.2.3.4.5]
/ / pure functions
numbers.slice(0.3)
// => [1, 2, 3]
numbers.slice(0.3)
// => [1, 2, 3]
numbers.slice(0.3)
// => [1, 2, 3]
// impure function
numbers.splice(0.3)
// => [1, 2, 3]
numbers.splice(0.3)
/ / = > [4, 5]
numbers.splice(0.3)
/ / = > []
Copy the code
  • Functional programming does not preserve the middle of the calculation, so variables are immutable (stateless)
  • We can hand off the results of one function to another

Benefits of pure functions

  • cacheable
    • Because pure functions always have the same result on the same input, the result of a pure function can be cached
const _ = require('lodash')
function getArea (r) {
   return Math.PI * r * r
}
let getAreaWithMemory = _.memoize(getArea)
console.log(getAreaWithMemory(4))
Copy the code
  • Create your own memoize function
function memoize (f) {
let cache = {}
return function () {
        let arg_str = JSON.stringify(arguments)
        cache[arg_str] = cache[arg_str] || f.apply(f, arguments)
        return cache[arg_str]
    }
}
Copy the code
  • testable
    • Pure functions make testing easier
  • Parallel processing
    • Parallel manipulation of shared memory data in a multithreaded environment is likely to cause unexpected problems
    • Pure functions do not need access to shared memory data, so they can run at will in parallel (Web workers)

Purely functional side effect

  • Pure functions: For the same input you always get the same output without any observable side effects
/ / not pure
let mini = 18
function checkAge (age) {
    return age >= mini
}
// Pure (hardcoded, later can be solved by Currization)
function checkAge (age) {
    let mini = 18
    return age >= mini
}
Copy the code

Side effects make a function impure (as in the example above). Pure functions return the same output based on the same input, and can have side effects if the function depends on external state and cannot guarantee the same output. Sources of side effects:

  • The configuration file
  • The database
  • Get user input

… All external interactions may bring side effects, which also reduce the generality of the method and make it unsuitable for expansion and reusability. At the same time, side effects will bring security risks to the program and uncertainty to the program. However, side effects cannot be completely prohibited, and they should be controlled as much as possible.