Pure functions

concept

The same input must give the same output. Here’s an example:

Array. Slice (0, 2); // the pure function array.splice(0,2); // An impure function because splice changes the arrayCopy the code

Pure function related tool library: LoDash

advantages

  • cacheable

    function getArea(r) { console.log(r); return Math.PI * r * r; } function memoize(fn) { let cache = {}; return function () { let key = JSON.stringify(arguments); cache[key] = cache[key] || fn.apply(fn, arguments); return cache[key]; } } let getAreaWithMemoize = memoize(getArea); console.log(getAreaWithMemoize(2)); // r console.log(getAreaWithMemoize(2)) is printed only on the first run; console.log(getAreaWithMemoize(2));Copy the code
  • testable

  • Parallel processing

    • Parallel manipulation of data in shared memory in a multithreaded environment (thread unsafe) can have unexpected consequences, known as side effects
    • Pure functions are stateless and do not depend on external data, so they can be arbitrarily executed in parallel

Side effects

A pure function is a stateless function. The same input always yields the same output. If the function relies on external data, there is no guarantee that it will have the same output, resulting in side effects.

  • External data include:
    • The database
    • User input
    • The configuration file