Why learn functional programming?

  • The core understanding is that class libraries are written for easy reuse
  • FP (Functional Programming) is the programming paradigm (style)

The point is: one-to-one mapping, the same input has the same output (pure function)

Higher-order functions

  • The function is passed as an argument and returned as a result
  • Abstraction helps us screen out the details and focus only on our own goals

Write the advanced functions every, some, forEach

// every
const every = (array, fn) = > {
  let result = true
  for (let value of array) {
    result = fn(value)
    if(! result) {break}}return result
}

// some
const some = (array, fn) = > {
  let result = false
  for (let value of array) {
    result = fn(value)
    if (result) {
      break}}return result
}
Copy the code

Closure (Closure)

  • It’s a function’s capture of a variable in a higher scope
  • Closure lifetime: Values in closures do not disappear and remain in memory unless manually deleted. Closures can cause memory leaks if they are abused. 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 members of the outer function
    function salary(base) {
      return function (number) {
        return base + number
      }
    }

    let salaryLever1 = salary(12000)
    let salaryLever2 = salary(15000)

    console.log(salaryLever1(2000))
    console.log(salaryLever2(5000))
Copy the code

Pure functions

  • The same input always yields the same output, similar to a one-to-one mapping in mathematics
  • Create my own memoize function:
// memory function
const _ = require('lodash')

function getArea (r) {
  console.log(r)
  return Math.PI * r * r
}

// let getAreaWithMemory = _.memoize(getArea)
// console.log(getAreaWithMemory(4))
// console.log(getAreaWithMemory(4))
// console.log(getAreaWithMemory(4))


// Simulate the implementation of memoize method

function memoize (f) {
  let cache = {}
  return function () {
    let key = JSON.stringify(arguments)
    cache[key] = cache[key] || f.apply(f, arguments)
    return cache[key]
  }
}

let getAreaWithMemory = memoize(getArea)
console.log(getAreaWithMemory(4))
console.log(getAreaWithMemory(4))
console.log(getAreaWithMemory(4))
Copy the code