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

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.

主站蜘蛛池模板: 安平县| 高密市| 新宾| 突泉县| 滦南县| 黔西县| 咸宁市| 清丰县| 古交市| 江永县| 酉阳| 上犹县| 图片| 泰安市| 双鸭山市| 墨玉县| 凤庆县| 新民市| 南部县| 灌南县| 紫阳县| 灌南县| 开封县| 汕尾市| 察哈| 元氏县| 余江县| 湘潭市| 错那县| 琼中| 玉龙| 闵行区| 股票| 麟游县| 紫阳县| 武穴市| 四平市| 普定县| 平武县| 广饶县| 宁化县|