Today to talk about pure and impure functions Functions

Pure function is defined:

  1. If you call the function parameters are the same, always return the same result. It does not rely upon a program change in any state or function of the external data during execution, you must rely only on its input parameters.

  2. This function does not produce any observable side effects, such as network requests, data input and output devices or mutant (mutation).

This is a pure function. If a function in line with the above two requirements, it is a pure function. Otherwise not pure function;

Examples:

例子1:function priceAfterTax(productPrice) { return (productPrice * 0.20) + productPrice;}

priceAfterTax result of this function depend only parameter productPrice, not dependent on any external input, external does not change any data, no side effects.

So, this is a pure function;

Example 2:

was dachshund = 20;

function calculateTax(productPrice) { return (productPrice * (tax/100)) + productPrice; }

PriceAfterTax result of this function, depending on externally defined variables tax, and the function can not rely purely external variables. It does not satisfy the first requirement definition, and therefore this function is impure.

 

Guess you like

Origin www.cnblogs.com/nimon-hugo/p/12559129.html