官术网_书友最值得收藏!

Pure functions

FP introduces a number of concepts and principles that will help us to improve the predictability of our code. In this section, we are going to learn about one of these core concepts—pure functions.

A function can be considered pure when it returns a value that is computed using only the arguments passed to it. Also, a pure function avoids mutating its arguments or any other external variables. As a result, a pure function always returns the same value given the same arguments, independently of when it is invoked.

The isIndexPage function declared in the preceding section is not a pure function because it accesses the pathname variable, which has not been passed as an argument to the function. We can transform the preceding function into a pure function by rewriting it as follows:

function isIndexPage(pathname: string) {
return pathname === "/";
}

Even though this is a basic example, we can easily perceive that the newer version is much easier to predict. Pure functions help us to make our code easier to understand, maintain, and test.

Imagine that we wanted to write a unit test for the impure version of the isIndexPage function. We would encounter some problems when trying to write a test because the function uses the window.location object. We could overcome this issue by using a mocking framework, but it would add a lot of complexity to our unit tests just because we didn't use a pure function.

On the other hand, testing the pure version of the isIndexPage function would be straightforward, as follows:

function shouldReturnTrueWhenPathIsIndex(){
let expected = true;
let result = isIndexPage("/");
if (expected !== result) {
throw new Error('Expected ${expected} to equals ${result}');
}
}

function shouldReturnFalseWhenPathIsNotIndex() {
let expected = false;
let result = isIndexPage("/someotherpage");
if (expected !== result) {
throw new Error('Expected ${expected} to equals ${result}');
}
}

Now that we understand how functional programming helps us to write better code by avoiding state mutations, we can learn about side-effects and referential transparency.

主站蜘蛛池模板: 绥德县| 海淀区| 卢龙县| 璧山县| 天水市| 泰顺县| 乳山市| 万山特区| 临夏县| 昔阳县| 天津市| 昆山市| 新河县| 西和县| 保山市| 西充县| 马尔康县| 璧山县| 铜山县| 赤城县| 乌兰察布市| 新源县| 咸宁市| 阿勒泰市| 航空| 达孜县| 图们市| 五寨县| 井研县| 永修县| 西林县| 化德县| 景德镇市| 长武县| 鸡东县| 神农架林区| 壶关县| 清水河县| 阿勒泰市| 苏尼特右旗| 文成县|