Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

preface

So far, we’ve reviewed functional programming, closures, higher-order functions, and other function-related concepts. Next, we’ll cover pure functions, Loadsh, the benefits of pure functions, and the side effects of pure functions

The issue of

  • Functional programming, higher order functions
  • closure

Pure functions

The concept of pure functions

The same input will always get the same output, without any observable side effects

Common pure functions for parsing

We parse through arrays of slice and splice

  • An array ofsliceandspliceThey are: pure function and impure function
    • sliceReturns the specified part of the array, without changing the array
    let array = [1.2.3.4.5.6.7.8]
    console.log(array.slice(0.3)) / / [1, 2, 3]
    console.log(array.slice(0.3)) / / [1, 2, 3]
    console.log(array.slice(0.3)) / / [1, 2, 3]
    Copy the code

    The output is the same three times. Let’s recall the concept of a pure function:The same input (argument) will always produce the same output, sosliceIt’s a pure function.

    • spliceOperating on an array returns that array, changing the original array
    let array = [1.2.3.4.5.6.7.8]
    console.log(array.splice(0.3)) / / [1, 2, 3]
    console.log(array.splice(0.3)) / / [4, 5, 6]
    console.log(array.splice(0.3)) / / [7, 8]
    Copy the code

    The output is different three times, sospliceIt’s an impure function.

Let’s write a pure function ourselves

function getSum (n1, n2) {
    return n1 + n2
}
console.log( getSum(1.2))/ / 3
console.log( getSum(1.2))/ / 3
console.log( getSum(1.2))/ / 3
Copy the code
  • Functional programming does not preserve intermediate settlement results, so variables are immutable (stateless)
  • We can hand off the results of one function to another function for processing

Lodash

Lodash is a consistent, modular, high-performance JavaScript utility library.

The benefits of pure functions

  • cacheable

    • Because pure functions always produce the same result for the same input, the result can be stored

      Example: to find the circle area for case output

      Use the library of functions: Memoize for LoDash

      // memory function
      const _ = require('lodash')
      function getArea(r) {
          console.log(r)
          return Math.PI * r * r
      }
      let area = _.memoize(getArea)
      console.log(area(4))
      console.log(area(4))
      console.log(area(4))
      Copy the code

      Because our function is relatively simple, let’s look at the output here in getArea

      4
      50.26548245743669
      50.26548245743669
      50.26548245743669
      Copy the code

      How do we implement memoize as we obviously only output the radius of the circle once

    • Simulate memoize implementation

      function memoize(f) {
          // We need to define an object internally and store it
          let cache = {}
           // When we return the result, we need to make a judgment first
           // If the result is already in the cache, it is returned directly, if not, execute the method and store the result
          return function() {
              // arguments is a pseudo-array
              let key = JSON.stringify(arguments)
              cache[key] = cache[key] || f.apply(f,arguments)
              return cache[key]
          }
      }
      Copy the code

      Ok, by now our Memoize is finished, let’s test it

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

      Output result:

      4
      50.26548245743669
      50.26548245743669
      50.26548245743669
      Copy the code

      Ok, the output is the same, which shows that there is no problem with our thinking

  • testable

    • Pure functions make testing easier: Pure functions always have inputs and outputs for unit testing
  • Parallel processing

    • Parallel manipulation of shared memory data in a multithreaded environment is likely to cause unexpected problems
    • Pure functions do not require a range of shared memory data, so in parallel environment can run pure functions (Web Worker) arbitrary, there will be some students say that js is not single thread?? Learn more about Web workers after ES6, but most of them are single threaded.

Side effects of pure functions:

/ / not pure
let mini= 18
function checkAe(age) {
    return age >= mini
}
// a pure function
function checkAge(age) {
    let mini = 18
    return age >= mini
}
Copy the code

Side effects can cause a function to become impure (as in the example above). Pure functions depend on the same output, and the same output cannot be guaranteed if the function depends on external states.

Sources of side effects

  • The configuration file
  • The database
  • Get user input

All external interactions are likely to bring side effects, which also make the method less universal and not suitable for expansion and usability; At the same time, side effects will bring security risks to the program and bring uncertainty to the program, but side effects cannot be completely prohibited, as far as possible to control them in a safe and controllable range.

conclusion

  • Pure functions have the same input and always get the same output without any observable side effects, and can improve performance to some extent by storing the same input data. However, we need to pay attention to some security risks caused by side effects.